- how to write the correct data type to a particular value?
Last active
November 16, 2024 03:35
-
-
Save anonaba/1d1d69d1ca8bcfea0d6fe02995daeb1e to your computer and use it in GitHub Desktop.
PostgreSQL Notes
PostgreSQL provides a wide range of data types to store different kinds of data. Choosing the correct data type for a value depends on the nature of the data and how you intend to use it. Below is a guide to match values with appropriate PostgreSQL data types:
- Integer Types: Use for whole numbers.
SMALLINT
: For very small numbers (e.g.,-32,768
to32,767
).INTEGER
orINT
: For typical whole numbers (e.g.,-2,147,483,648
to2,147,483,647
).BIGINT
: For large whole numbers.
- Decimal/Precision Numbers: Use for values requiring precision, like prices or measurements.
NUMERIC(precision, scale)
: For exact precision. (e.g.,NUMERIC(10, 2)
for up to 10 digits, 2 after the decimal).REAL
orFLOAT
: For approximate floating-point numbers.
- Serial Types: For auto-incrementing integers.
SERIAL
,BIGSERIAL
: Use for primary keys.
- Fixed/Variable Length Strings:
CHAR(n)
orCHARACTER(n)
: For fixed-length strings. Pads with spaces if the input is shorter.VARCHAR(n)
orCHARACTER VARYING(n)
: For variable-length strings with a maximum length.TEXT
: For unlimited-length strings.
BOOLEAN
: Use for true/false values.- Accepts
TRUE
,FALSE
,NULL
, or equivalents like1
(true) and0
(false).
- Accepts
- Date:
DATE
: For calendar dates (e.g.,2024-11-16
).
- Time:
TIME
: For times of day (e.g.,14:30:00
).TIME WITH TIME ZONE
: Includes the time zone.
- Timestamps:
TIMESTAMP
: For date and time together (e.g.,2024-11-16 14:30:00
).TIMESTAMP WITH TIME ZONE
: For date, time, and timezone.
- Intervals:
INTERVAL
: For time intervals (e.g.,1 year 2 months
).
- JSON: For storing JSON-formatted text (e.g.,
{"key": "value"}
). - JSONB: For a binary JSON format, enabling faster queries and indexing.
datatype[]
: For storing arrays of a specific type (e.g.,INTEGER[]
,TEXT[]
).
ENUM
: Define a static set of values (e.g.,CREATE TYPE mood AS ENUM ('happy', 'sad', 'neutral');
).
- For spatial data:
POINT
,LINE
,CIRCLE
,POLYGON
.
- UUID: For universally unique identifiers.
- BYTEA: For binary data like images or files.
- ARRAY: For arrays of any data type.
- XML: For storing XML data.
Value | Recommended Data Type |
---|---|
42 |
INTEGER |
1234567890123 |
BIGINT |
29.99 |
NUMERIC(5, 2) or REAL |
'Hello, World!' |
TEXT or VARCHAR(50) |
TRUE or FALSE |
BOOLEAN |
2024-11-16 |
DATE |
14:30:00 |
TIME |
2024-11-16 14:30:00 |
TIMESTAMP |
{'red', 'blue'} |
TEXT[] |
{"key": "value"} |
JSON or JSONB |
Would you like help crafting SQL statements with these data types?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment