Sub topic 1
How PostgreSQL types work
PostgreSQL assigns a data type to every column and to every value in an expression. A type describes what a value means, how PostgreSQL stores it, which operations are valid, and how comparisons work.
Prerequisites
This chapter assumes that you know basic SELECT, INSERT, and CREATE TABLE statements. You should also know what a table, column, and constraint are, and have access to psql or another PostgreSQL client.
A type is a contract
A column definition is a contract between your schema and your data. For example, integer accepts whole numbers, while date accepts calendar dates. PostgreSQL can then reject values that do not fit the contract.
CREATE TABLE measurements (
id integer,
label text,
reading numeric(8, 2),
measured_on date
);
INSERT INTO measurements (id, label, reading, measured_on)
VALUES (1, 'temperature', 21.50, DATE '2026-01-15');The numeric(8, 2) declaration includes a type modifier. The first number is the maximum precision, or total number of digits. The second is the scale, or number of digits after the decimal point. Type modifiers refine a base type without creating a completely new type.
A constraint adds another rule. For example, NOT NULL requires a value, and CHECK rejects values that fail a condition. Types and constraints work together: the type checks the general shape of a value, while the constraint checks a business rule.
How PostgreSQL uses types
PostgreSQL uses types when it parses expressions, chooses operators, stores values, and returns query results. The same operator can behave differently for different types.
SELECT 2 + 3 AS integer_sum,
'2'::integer + 3 AS converted_sum,
2 || ' apples' AS text_result;The ::integer expression is an explicit cast. It tells PostgreSQL to convert the text value '2' into an integer before adding it. The concatenation operator, ||, produces text in the final expression.
You can inspect a value's type with pg_typeof:
SELECT pg_typeof(2) AS number_type,
pg_typeof('2'::integer) AS converted_type,
pg_typeof(DATE '2026-01-15') AS date_type;SQL string literals often begin with an unknown type. PostgreSQL resolves that type from context, such as the target column or an operator. Explicit casts make important conversions clear and prevent surprising results.
Common errors
A value can have the right general meaning but the wrong type. PostgreSQL may reject an implicit conversion when it cannot prove that the conversion is safe. Use an explicit cast and read the error message carefully. Errors such as invalid input syntax usually mean that the text cannot be parsed as the requested type.
Exercise
What does numeric(10, 2) specify?
Show answer
It specifies a numeric value with up to 10 total digits, including up to 2 digits after the decimal point.