Sub topic 2
Integers and identity columns
This chapter assumes you can write basic SELECT, INSERT and CREATE TABLE statements and run them in psql or another client. It covers PostgreSQL's three integer types, how overflow behaves, and how identity columns generate keys. Exact decimals are the next chapter, so fractional values are out of scope here.
The three integer types
PostgreSQL has three integer types. Each stores whole numbers in a fixed number of bytes.
| Type | Aliases | Storage | Range |
|---|---|---|---|
| `smallint` | `int2` | 2 bytes | -32,768 to 32,767 |
| `integer` | `int`, `int4` | 4 bytes | -2,147,483,648 to 2,147,483,647 |
| `bigint` | `int8` | 8 bytes | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
All three are signed. PostgreSQL has no unsigned integer types. If a value must never be negative, add a CHECK (col >= 0) constraint, or use a domain, which a later chapter covers.
integer is the usual default for counts and quantities. smallint saves two bytes per value, but alignment padding often removes the saving, so use it for a real domain reason, such as a small status code, and not to trim storage. bigint is the safe choice for anything that grows without a natural bound, especially surrogate keys.
Overflow raises an error
PostgreSQL does not wrap around silently. A value outside the range of the target type raises an error.
SELECT 2147483647::integer + 1;
-- ERROR: integer out of range
SELECT 2147483647::bigint + 1;
-- 2147483648
SELECT 40000::smallint;
-- ERROR: smallint out of rangeThe first statement fails because both operands are integer, so the addition happens in integer. In the second, the bigint operand makes the result bigint. An integer literal is integer if it fits, bigint if it is larger, and numeric if it is larger still.
An overflow error in production is usually a key column that outgrew integer. At 2.1 billion rows the inserts start failing. Changing the column type later with ALTER TABLE ... ALTER COLUMN ... TYPE bigint rewrites the whole table and holds a strong lock while it runs. Choosing bigint up front costs 4 extra bytes per row and avoids that migration.
Division and arithmetic
Dividing two integers gives an integer, and the fraction is discarded toward zero.
SELECT 7 / 2 AS int_div,
-7 / 2 AS negative_div,
7 % 2 AS remainder,
7 / 2.0 AS decimal_div;This returns 3, -3, 1 and 3.5000000000000000. The last column is numeric because 2.0 is a numeric literal. Integer division is a common source of wrong percentages and averages. Cast one operand when you need a fractional result.
Arithmetic on mixed integer types promotes to the wider type. smallint + integer gives integer, and integer + bigint gives bigint.
SELECT pg_typeof(1::smallint + 1::integer) AS a,
pg_typeof(1::integer + 1::bigint) AS b;This returns integer and bigint. The function pg_typeof is useful whenever you are unsure what type an expression produces.
Identity columns
A surrogate key is an identifier with no business meaning, generated by the database. Identity columns are the standard SQL way to create one. Each identity column is backed by a sequence, a database object that hands out increasing numbers.
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()
);The id column is a bigint, so it will not overflow in practice. PRIMARY KEY makes it unique and not null, and creates an index. The other columns use types covered in later chapters.
ALWAYS versus BY DEFAULT
There are two forms of identity column.
GENERATED ALWAYS AS IDENTITYrejects explicit values for the column unless you addOVERRIDING SYSTEM VALUEto theINSERT.GENERATED BY DEFAULT AS IDENTITYuses the sequence only when you do not supply a value. An explicit value is accepted.
INSERT INTO orders (customer_email, total)
VALUES ('[email protected]', 19.99);
INSERT INTO orders (id, customer_email, total)
VALUES (100, '[email protected]', 5.00);
-- ERROR: cannot insert a non-DEFAULT value into column "id"
-- DETAIL: Column "id" is an identity column defined as GENERATED ALWAYS.
INSERT INTO orders (id, customer_email, total)
OVERRIDING SYSTEM VALUE
VALUES (100, '[email protected]', 5.00);ALWAYS protects you from application code that supplies its own ids. That protects against collisions with the sequence. Use BY DEFAULT when you load data with existing ids, for example in a migration, and accept that you must then keep the sequence ahead of the loaded values.
After loading explicit ids, the sequence does not know about them. The next generated id could collide with a loaded one and fail on the primary key. Move the sequence forward with setval:
SELECT setval(
pg_get_serial_sequence('orders', 'id'),
(SELECT max(id) FROM orders)
);Getting the generated value back
Use RETURNING to read the generated id in the same statement. It avoids a second query and is safe under concurrency.
INSERT INTO orders (customer_email, total)
VALUES ('[email protected]', 42.00)
RETURNING id;Identity versus serial
Older code uses serial, bigserial and smallserial. These are shorthand that create an integer column, a sequence, and a DEFAULT nextval(...). Identity columns do the same job with better behavior.
| Feature | `serial` | Identity column |
|---|---|---|
| Part of the SQL standard | No | Yes |
| Prevents explicit values | No | Yes, with `ALWAYS` |
| Sequence tied to the column on copy and drop | Partly | Yes |
| Permissions on the sequence | Granted separately | Follow the table |
For new tables, prefer identity columns. You will still see serial in existing schemas, and it works the same way at runtime.
Sequences have gaps
A sequence guarantees increasing values, not consecutive ones. Gaps are normal and you should not try to remove them. Sequence values are never handed back, so any of these leaves a gap:
- A transaction that rolls back after taking a value.
- A failed insert, such as one that violates a unique constraint.
- A server crash, because PostgreSQL pre-allocates some values.
BEGIN;
INSERT INTO orders (customer_email, total) VALUES ('[email protected]', 1.00);
ROLLBACK;
INSERT INTO orders (customer_email, total) VALUES ('[email protected]', 2.00)
RETURNING id;The id returned by the last statement skips the value consumed by the rolled-back insert.
Because of this, never use an id to count rows, and never treat a missing id as a deleted row. Use count(*) for counts. If a legal requirement demands gapless numbers, such as invoice numbers in some jurisdictions, a plain sequence is the wrong tool. You need a separate counter table updated inside the same transaction, which serializes writers.
Controlling sequence options
Identity columns accept sequence options. You can set a start value and an increment.
CREATE TABLE tickets (
id integer GENERATED BY DEFAULT AS IDENTITY (START WITH 1000 INCREMENT BY 1) PRIMARY KEY,
title text NOT NULL
);Inspect or restart an identity later with ALTER TABLE:
ALTER TABLE tickets ALTER COLUMN id RESTART WITH 5000;TRUNCATE ... RESTART IDENTITY resets identity sequences as part of emptying a table. A plain TRUNCATE leaves them where they were.
Integer keys and other options
The diagram shows how an insert reaches the stored row.
Integer keys are small and fast to compare and index, and they sort in insertion order, which keeps index inserts at the right edge of the B-tree. Their drawbacks are that they reveal how many rows exist and are easy to guess, and they are only unique within one database. If ids must be generated in several places or must not be guessable, consider the UUID type, which a later chapter covers. Do not expose sequential ids as the only protection for a resource. Check authorization on every request.
Common mistakes
- Using
integerfor a key on a table that may pass two billion rows. - Expecting
7 / 2to return3.5. - Relying on ids being gapless or on id order matching commit order. Under concurrency, a lower id can commit after a higher one.
- Loading explicit ids into a
BY DEFAULTcolumn and forgetting to advance the sequence. - Using
floatorrealfor counts. Floating-point types are for approximate measurements and are covered in a later chapter.
Exercise
A table has id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY. You bulk-load 10,000 rows with explicit ids 1 to 10000, then insert a row without an id. The insert fails with a duplicate key error on id. Why did it fail, and what statement fixes it?
Show answer
The explicit ids did not use the sequence, so the sequence still returned 1 and collided with the loaded row. Advance the sequence past the maximum id, for example SELECT setval(pg_get_serial_sequence('t', 'id'), (SELECT max(id) FROM t));. After that the next generated id is 10001.
Exercise
What does SELECT 2147483647 + 1; return, and what does SELECT 2147483647::bigint + 1; return?
Show answer
The first statement raises ERROR: integer out of range, because both operands are integer and the sum does not fit in 4 bytes. The second returns 2147483648, because the bigint operand makes the addition happen in bigint.
Exercise
You roll back a transaction that inserted a row into a table with an identity key. Will the next insert reuse the id that the rolled-back insert consumed?
Show answer
No. Sequence values are not returned on rollback, so the next insert gets the following value and the table has a gap. Gaps are normal. If you need gapless numbers, use a counter table updated within the transaction instead of a sequence.