Sub topic 1
How PostgreSQL types work
Prerequisites
This chapter assumes you can write CREATE TABLE and INSERT statements, run queries in psql, and read a table definition. Every column has a type, and the type decides what values it accepts, how much space it uses, and how comparisons and arithmetic behave.
How PostgreSQL types work
A type sets the rules for a column. PostgreSQL rejects values that do not fit the type, and it applies type-specific behavior to operators such as + and =. Some types take a modifier in parentheses, such as numeric(12,2), which limits precision or length.
Integers and identity columns
Use bigint for row IDs that may grow large. An integer holds values up to about 2.1 billion, and a bigint holds up to about 9.2 quintillion. An identity column makes PostgreSQL assign the value for you.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_email text NOT NULL,
total numeric(12,2) NOT NULL CHECK (total >= 0)
);
INSERT INTO orders (customer_email, total) VALUES ('[email protected]', 19.99);Exact decimals with numeric
numeric(p,s) stores exact decimal values. Here p is the total number of digits and s is the number of digits after the decimal point. So numeric(12,2) holds up to ten digits before the point and two after it. Use numeric for money and any value where rounding errors are unacceptable.
Floating-point rounding
real and double precision store binary approximations. They are fast, but some decimal values cannot be represented exactly.
SELECT
0.1::double precision + 0.2::double precision = 0.3::double precision AS float_equal,
0.1::numeric + 0.2::numeric = 0.3::numeric AS numeric_equal;This returns false for the float comparison and true for the numeric one. Use floating-point types for measurements and scientific values, and never compare them with =.
Text, varchar and char
text stores strings of any length. varchar(n) stores up to n characters and rejects longer values. char(n) pads shorter values with spaces to exactly n characters. In PostgreSQL, text and varchar without a limit perform the same, so prefer text unless a length rule belongs in the schema. Avoid char(n) in new schemas because its padding surprises most readers.
> Note: a value that is too long for varchar(n) causes an error. PostgreSQL does not truncate it silently.
Exercise
Exercise
Which type should store a product price of 1234.56 exactly, and why?
Show answer
numeric(6,2). It stores exact decimal digits, so 1234.56 is kept precisely. A double precision value could round to a nearby binary approximation.