Sub topic 1
How PostgreSQL types work
Prerequisites
This chapter assumes you can do the following:
- Run
SELECT,INSERTandCREATE TABLEstatements inpsqlor another PostgreSQL client. - Explain what a table, a column and a constraint are.
- Read a short error message and match it to the statement that caused it.
No earlier chapter is needed. Later chapters cover each type family in detail. This chapter gives you the model they all share.
Every value has a type
PostgreSQL is strongly typed. Every column, expression result, function argument and literal has a data type. The type decides three things:
- Which values are valid. An
integercannot hold'abc'. - Which operators and functions apply. You can add two integers, but not two booleans.
- How the value is stored and compared. Text sorts by collation rules, and numbers sort by magnitude.
The function pg_typeof() shows the type of any expression:
SELECT pg_typeof(1) AS int_literal,
pg_typeof(1.5) AS decimal_literal,
pg_typeof(5000000000) AS big_literal,
pg_typeof(true) AS bool_literal,
pg_typeof(now()) AS now_type,
pg_typeof('a'::text) AS text_type;The result is integer, numeric, bigint, boolean, timestamp with time zone and text. Notice that 1.5 is numeric, not a floating-point type. The parser picks the smallest type that fits a numeric literal: integer, then bigint, then numeric.
Type families
PostgreSQL ships with many built-in types, grouped into families. The catalog pg_type records each one, including users' own types.
| Family | Examples | Typical use |
|---|---|---|
| Numeric | `smallint`, `integer`, `bigint`, `numeric`, `real`, `double precision` | Counts, money, measurements |
| Character | `text`, `varchar(n)`, `char(n)` | Names, descriptions, codes |
| Boolean | `boolean` | Flags, three-valued logic |
| Date and time | `date`, `time`, `timestamp`, `timestamptz`, `interval` | Events, durations |
| Identifier and binary | `uuid`, `bytea` | Keys, raw bytes |
| Structured | `jsonb`, arrays, composite types, ranges | Nested or multi-valued data |
| Constrained | enums, domains | Restricted sets of values |
| Network | `inet`, `cidr`, `macaddr` | Addresses |
You can inspect the catalog directly:
SELECT typname, typlen, typcategory
FROM pg_type
WHERE typname IN ('bool', 'int4', 'int8', 'text')
ORDER BY typname;The internal names differ from the SQL names. int4 is integer, int8 is bigint and bool is boolean. The typlen column is the fixed size in bytes. A value of -1 means variable length, as with text. Error messages and some catalog views use the internal names, so you should recognize both.
Fixed-width and variable-width types
Fixed-width types such as integer (4 bytes) and bigint (8 bytes) always use the same space. Variable-width types such as text, numeric and jsonb use space that depends on the value. Large variable-width values are compressed or moved out of the main table row automatically, a mechanism called TOAST. You can check the stored size of a value with pg_column_size():
SELECT pg_column_size(1::integer) AS int_bytes,
pg_column_size(1::bigint) AS bigint_bytes,
pg_column_size('hello'::text) AS text_bytes;This returns 4, 8 and 6. The text value takes its five characters plus a one-byte length header. Storage size matters because smaller rows mean more rows per page, so scans read less data and indexes stay smaller.
Type modifiers
A type modifier is a parameter written in parentheses after a type name. It narrows the type without creating a new one. Common modifiers:
varchar(n)limits length toncharacters.numeric(p,s)sets total digitspand digits after the decimal points.timestamp(p)sets the number of fractional-second digits, up to 6.
The modifier is stored with the column, not in the type itself. Create a table and look at it:
CREATE TABLE modifier_demo (
code varchar(5),
amount numeric(5,2)
);
SELECT attname, format_type(atttypid, atttypmod) AS declared_type
FROM pg_attribute
WHERE attrelid = 'modifier_demo'::regclass
AND attnum > 0
AND NOT attisdropped
ORDER BY attnum;The output shows character varying(5) and numeric(5,2). The column atttypmod holds the encoded modifier, and format_type() turns it back into readable text.
Modifiers are enforced when a value is stored, and the two examples behave differently:
INSERT INTO modifier_demo VALUES ('abc', 12.345); -- stored as 12.35
INSERT INTO modifier_demo VALUES ('abcdef', 1); -- ERROR: value too long for type character varying(5)
INSERT INTO modifier_demo VALUES ('abc', 1234.5); -- ERROR: numeric field overflowThe first statement succeeds because numeric rounds extra decimal places to fit the scale. The second fails because PostgreSQL does not silently truncate text. The third fails because 1234.5 needs four digits before the decimal point, and numeric(5,2) allows only three.
How a column is defined
A column definition has three layers. The type decides the value domain. The modifier narrows it. Constraints such as NOT NULL and CHECK add rules that no type can express.
Here is that layering in a real table:
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),
is_paid boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now()
);Each choice has a reason. bigint avoids running out of keys. text imposes no arbitrary length. numeric(12,2) keeps money exact. boolean has two states. timestamptz stores an unambiguous instant. The CHECK rejects negative totals, which the type would allow.
Literals, unknown types and resolution
A quoted literal such as '42' starts as type unknown. PostgreSQL resolves it from context. Beside an integer, it is parsed as an integer. In a date column, it is parsed as a date. This is why this works:
SELECT '42' + 1 AS answer;The result is 43. The literal '42' takes the type integer because the other operand is an integer. If the text cannot be parsed, you get an error such as invalid input syntax for type integer: "a".
A value that already has a definite type is not converted this freely. A text column does not become an integer just because you add one to it:
CREATE TABLE strict_demo (label text);
INSERT INTO strict_demo VALUES ('42');
SELECT label + 1 FROM strict_demo;
-- ERROR: operator does not exist: text + integerThe error is a type error, not a data error. No operator + is defined for the pair text and integer. The fix is an explicit cast, label::integer + 1, which the casting chapter covers.
PostgreSQL chooses an operator by looking at the argument types, then checking for an exact match, then for implicit conversions. Implicit conversions exist only in safe directions, for example integer to bigint, or integer to numeric. Conversions that could lose information or surprise you, such as text to integer, need an explicit cast.
NULL has a type too
NULL stands for an unknown value and belongs to every type. A bare NULL is unknown until context fixes it. In a column, it takes the column's type. Any type can be NULL unless you add NOT NULL. Operators generally return NULL when any input is NULL, so NULL + 1 is NULL. The boolean chapter returns to this.
Common errors at a glance
| Message | Cause | Fix |
|---|---|---|
| `operator does not exist: text + integer` | No operator for that type pair | Cast one side explicitly |
| `invalid input syntax for type integer: "abc"` | Text cannot be parsed as the target type | Clean the data or choose another type |
| `value too long for type character varying(5)` | Text exceeds the `varchar(n)` modifier | Shorten the value or widen the limit |
| `numeric field overflow` | Too many integer digits for `numeric(p,s)` | Increase `p - s` |
| `integer out of range` | Value exceeds the 4-byte limit | Use `bigint` |
Exercise
A column is declared price numeric(6,2). What happens when you insert 12.349, and what happens when you insert 12345.67? Give the stored value or the error for each.
Show answer
12.349 is rounded to the declared scale and stored as 12.35. 12345.67 has five digits before the decimal point, but numeric(6,2) allows only 6 - 2 = 4, so PostgreSQL raises numeric field overflow.
Exercise
Why does SELECT '42' + 1 work while SELECT label + 1 fails when label is a text column?
Show answer
The quoted literal has type unknown and takes the type integer from the other operand. A text column already has a definite type, and PostgreSQL has no + operator for text and integer and no implicit cast between them. You need label::integer + 1.