Sub topic 5
Generating key values
This chapter assumes you can write CREATE TABLE, INSERT, and basic SELECT statements, and that you know a primary key must be unique and not null. It also assumes you have read the chapter on natural versus surrogate keys. Here you learn how the database produces surrogate key values, which options exist, and where each one fails.
Why let the database generate keys
A surrogate key has no business meaning, so nothing in your data supplies its value. If application code picks the next number, two sessions can pick the same one. The database can hand out values safely under concurrent inserts, so you let it do that.
There are three common approaches:
- Identity columns, which are the SQL standard way to auto-number a column.
- Sequences, which are separate counter objects that you can share or call directly.
- UUIDs, which are 128-bit identifiers that can be generated anywhere without coordination.
Identity columns
An identity column attaches an automatic counter to a column. PostgreSQL 10 and later supports the standard syntax:
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL
);
INSERT INTO customers (email, name)
VALUES ('[email protected]', 'Ana')
RETURNING customer_id;You leave customer_id out of the insert, and the database fills it in. RETURNING sends the new value back, so you can use it as the foreign key for child rows without a second query.
ALWAYS versus BY DEFAULT
The two forms differ in what happens when you supply a value yourself.
| Form | Explicit value in INSERT | Typical use |
|---|---|---|
| `GENERATED ALWAYS AS IDENTITY` | Rejected with an error unless you add `OVERRIDING SYSTEM VALUE` | New tables where only the database should assign keys |
| `GENERATED BY DEFAULT AS IDENTITY` | Accepted and used as given | Data loads and migrations that must keep existing key values |
-- Fails with GENERATED ALWAYS:
INSERT INTO customers (customer_id, email, name)
VALUES (500, '[email protected]', 'Bo');
-- Succeeds, but you take responsibility for the value:
INSERT INTO customers (customer_id, email, name)
OVERRIDING SYSTEM VALUE
VALUES (500, '[email protected]', 'Bo');Overriding does not move the counter. After you insert 500 by hand, the counter still hands out 1, 2, 3, and so on. When it reaches 500 you get a duplicate key error.
Sequences
A sequence is a database object that produces increasing numbers. An identity column uses one internally. You can also create and use one yourself:
CREATE SEQUENCE invoice_number_seq START WITH 1000;
SELECT nextval('invoice_number_seq'); -- 1000
SELECT nextval('invoice_number_seq'); -- 1001
SELECT currval('invoice_number_seq'); -- 1001, this session's last valueUse a standalone sequence when one counter must feed several tables, or when you need the number before you insert the row. Older PostgreSQL code often uses the SERIAL type, which creates a sequence and sets it as the column default. Prefer GENERATED ... AS IDENTITY in new code. It follows the SQL standard, and the sequence is tied to the column, so permissions and drops behave predictably.
Sequences do not roll back
A sequence is not transactional. Once nextval gives out a number, that number is spent, even if the transaction rolls back.
BEGIN;
INSERT INTO customers (email, name) VALUES ('[email protected]', 'Cy');
ROLLBACK;
INSERT INTO customers (email, name) VALUES ('[email protected]', 'Di');
-- Di's customer_id skips the value that Cy's rolled-back insert used.This is by design. Rolling a counter back would force concurrent sessions to wait on each other. Gaps also appear after crashes and failed inserts, for example one that violates the UNIQUE constraint on email. Never rely on keys being gapless. If a business rule needs gapless numbers, such as legal invoice numbering, generate them in a separate, carefully locked process and keep the surrogate key independent.
UUIDs
A UUID (universally unique identifier) is a 128-bit value, written like 3f2b8c1e-9a4d-4e7b-8c55-1d2a6f0b9e34. Because the chance of a collision is negligible, any application server, mobile client, or database can create one without asking a central counter.
CREATE TABLE devices (
device_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
label VARCHAR(100) NOT NULL
);gen_random_uuid() is built into PostgreSQL 13 and later. Older versions need the pgcrypto extension.
The trade-offs against integer keys:
- Size. A UUID takes 16 bytes. A
BIGINTtakes 8 and anINTEGERtakes 4. Every foreign key column and every index entry repeats that key, so the cost grows with the schema. - Index locality. Random UUIDs (version 4) insert at random positions in a B-tree index. That causes more page splits and cache misses than an ascending integer does. Time-ordered UUIDs (version 7) reduce the problem. PostgreSQL 18 adds
uuidv7(). On earlier versions, generate version 7 values in the application. - Readability. Integers are easier to read in logs and support tickets.
- Exposure. Sequential integers in URLs reveal how many rows exist and let people guess neighboring ids. Random UUIDs do not. Authorization checks are still required either way.
Choosing a type and size
Pick the integer width for the lifetime of the table, not for today. A 4-byte INTEGER tops out near 2.1 billion. A table that inserts 1,000 rows per second reaches that limit in about 25 days of continuous load, and changing the type later means rewriting the table and every column that references it. For tables that might grow large, use BIGINT.
CREATE TABLE events (
event_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
payload TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);A foreign key column must have a type compatible with the key it references. If events.event_id is BIGINT, a child table's event_id column must be BIGINT too. Declaring it INTEGER works until values pass 2.1 billion, then fails.
Common problems
- Duplicate key after a data load. You inserted explicit ids, and the counter lagged behind. Reset it with
SELECT setval(pg_get_serial_sequence('customers', 'customer_id'), (SELECT MAX(customer_id) FROM customers));. - Reading the key back with
MAX.SELECT MAX(customer_id)right after an insert can return another session's row. UseRETURNINGorcurrvalinstead. - Treating keys as ordered or gapless. Concurrent sessions can commit in a different order than they took numbers. Sort by a timestamp column when you need chronological order.
- Reusing keys. Do not reassign a deleted row's key to a new row. Old references in logs, caches, and external systems would then point to the wrong record.
Other databases
The ideas carry over, but the syntax differs.
| System | Auto-numbering syntax |
|---|---|
| PostgreSQL | `GENERATED ... AS IDENTITY`, `SERIAL`, sequences |
| MySQL | `AUTO_INCREMENT` on a column |
| SQL Server | `IDENTITY(1,1)`, plus `SEQUENCE` objects |
| Oracle | `GENERATED ... AS IDENTITY` (12c and later), sequences |
Exercise
A table uses GENERATED ALWAYS AS IDENTITY. A migration script copies 10,000 existing rows into it with their original ids, using OVERRIDING SYSTEM VALUE. The highest copied id is 10000. The next normal insert then fails with a duplicate key error. Why does it fail, and how do you fix it?
Show answer
Overriding the value does not advance the identity counter, so the counter still starts at 1 and eventually produces an id that the copied rows already use. Fix it by moving the counter past the highest existing id, for example with setval(pg_get_serial_sequence('table_name', 'id_column'), (SELECT MAX(id_column) FROM table_name)). Run this once after the load.
Exercise
Your application inserts 5 rows, and the transaction rolls back. The next successful insert gets id 6 instead of 1. Is this a bug, and should you "fix" the gap?
Show answer
It is not a bug. Sequences are not transactional, so values used inside a rolled-back transaction are not returned. Do not try to remove the gap. Gaps are normal, and the key only needs to be unique, not consecutive.