Generating Keys: Identity Columns, Sequences and UUIDs
How databases generate primary keys: identity columns (ALWAYS and BY DEFAULT), getting new keys back with RETURNING, why gaps appear, sequences shared between tables, SERIAL and AUTO_INCREMENT, random and time-ordered UUIDs, and how to choose between integer and UUID keys.
kvi5hnuCode Sprout team member11 min readOn this page
Most tables use a surrogate key (article 50): a meaningless value whose only job is to identify the row. Something has to generate those values, uniquely, even when many sessions insert at the same time. Databases offer two families of generators: increasing integers, from identity columns and sequences, and UUIDs, 128-bit values that can be generated anywhere.
This article covers both, how the application gets a new row's key back, and the behaviour that surprises people: gaps, collisions with manually inserted keys, and the performance of random UUIDs.
Identity columns
-- Identity columns: the database generates the key
CREATE TABLE tickets (
ticket_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
subject TEXT NOT NULL
);
-- RETURNING hands the new keys back to the application in the same statement
INSERT INTO tickets (subject)
VALUES ('Tent pole cracked'), ('Wrong size socks')
RETURNING ticket_id, subject;
-- GENERATED ALWAYS refuses explicit values unless you insist
INSERT INTO tickets (ticket_id, subject) VALUES (100, 'Manual');
INSERT INTO tickets (ticket_id, subject) OVERRIDING SYSTEM VALUE VALUES (100, 'Migrated from the old system');
SELECT ticket_id, subject FROM tickets ORDER BY ticket_id;
ticket_id | subject
-----------+-------------------
1 | Tent pole cracked
2 | Wrong size socks
(2 rows)
psql:/workspace/solution.sql:13: ERROR: cannot insert a non-DEFAULT value into column "ticket_id"
DETAIL: Column "ticket_id" is an identity column defined as GENERATED ALWAYS.
HINT: Use OVERRIDING SYSTEM VALUE to override.
ticket_id | subject
-----------+------------------------------
1 | Tent pole cracked
2 | Wrong size socks
100 | Migrated from the old system
(3 rows)
GENERATED ALWAYS AS IDENTITY is the SQL standard way to number rows automatically (PostgreSQL 10+, Oracle 12c+, Db2). Each insert that leaves the column out gets the next number: 1, 2, 3 and so on.
The application almost always needs the new key, to insert child rows or redirect to the new record. RETURNING (article 34) hands it back from the INSERT itself, with no second query and no race with other sessions. Other databases have their own ways:
| Database | Auto-numbered column | Get the new key |
|---|---|---|
| PostgreSQL | GENERATED ... AS IDENTITY (or legacy SERIAL) | RETURNING id |
| MySQL | AUTO_INCREMENT | LAST_INSERT_ID() |
| SQL Server | IDENTITY(1, 1) | OUTPUT inserted.id, or SCOPE_IDENTITY() |
| Oracle | GENERATED ... AS IDENTITY | RETURNING id INTO :var |
| SQLite | INTEGER PRIMARY KEY | RETURNING id (3.35+), or last_insert_rowid() |
LAST_INSERT_ID() and SCOPE_IDENTITY() are per connection, so they're safe with concurrent sessions. Never use SELECT MAX(id) to find a new key: another session may have inserted in between.
There are two kinds of identity column:
GENERATED ALWAYSrejects explicit values, as the insert of 100 shows. That protects the numbering from accidental manual keys. When you really need to supply a key, for example when migrating data from another system, writeOVERRIDING SYSTEM VALUE.GENERATED BY DEFAULTaccepts explicit values and generates one only when the column is omitted. It's more convenient, and more dangerous, as the next section shows.
PostgreSQL's older SERIAL type does the same job as BY DEFAULT, by creating a sequence and setting the column's default. It still works, but identity columns are the standard, have clearer ownership and permissions, and are the recommended choice in new tables.
Gaps are normal
-- Gaps are normal: rolled-back and failed inserts still use up values
CREATE TABLE notes (
note_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
body TEXT NOT NULL CHECK (length(body) > 0)
);
INSERT INTO notes (body) VALUES ('first');
BEGIN;
INSERT INTO notes (body) VALUES ('rolled back');
ROLLBACK;
INSERT INTO notes (body) VALUES (''); -- fails the CHECK
INSERT INTO notes (body) VALUES ('second');
SELECT note_id, body FROM notes ORDER BY note_id;
psql:/workspace/solution.sql:12: ERROR: new row for relation "notes" violates check constraint "notes_body_check"
DETAIL: Failing row contains (3, ).
note_id | body
---------+--------
1 | first
4 | second
(2 rows)
The rows are numbered 1 and 4. The rolled-back insert used 2, and the insert that failed its CHECK used 3. A generator hands out each number once, even if the transaction that took it never commits: giving numbers back would force every inserting session to wait for the others to finish, which would be far too slow.
So identity values are unique and increasing, but not gapless. Gaps also appear after deleted rows, after a server restart (generators cache blocks of values), and with INSERT ... ON CONFLICT (article 34), which takes a value before discovering the conflict. That's harmless for a surrogate key, whose only job is to be unique.
If a business rule needs gapless numbers, as some tax authorities require for invoices, don't use an identity column. Keep the last number in a table row and increment it inside the same transaction as the invoice insert, with UPDATE counters SET last_no = last_no + 1 ... RETURNING last_no. The row lock makes concurrent invoices wait for each other, which is the cost of having no gaps.
Explicit keys and BY DEFAULT
-- BY DEFAULT allows explicit values, which the generator doesn't know about
CREATE TABLE stores (
store_id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
city TEXT NOT NULL
);
INSERT INTO stores (store_id, city) VALUES (1, 'Pune'), (2, 'Leeds'); -- e.g. copied from another system
INSERT INTO stores (city) VALUES ('York'); -- the generator starts at 1
-- Move the generator past the existing keys, then it works
SELECT MAX(store_id) FROM stores;
ALTER TABLE stores ALTER COLUMN store_id RESTART WITH 3;
INSERT INTO stores (city) VALUES ('York') RETURNING store_id;
psql:/workspace/solution.sql:7: ERROR: duplicate key value violates unique constraint "stores_pkey"
DETAIL: Key (store_id)=(1) already exists.
max
-----
2
(1 row)
store_id
----------
3
(1 row)
With BY DEFAULT, the rows copied in with explicit keys 1 and 2 don't move the generator. The next automatic insert asks for 1, which already exists, and fails with a duplicate key error. Every automatic insert will keep failing until the generator passes the existing keys.
The fix is to restart the generator above the highest key: ALTER TABLE ... ALTER COLUMN ... RESTART WITH 3, or SELECT setval(pg_get_serial_sequence('stores', 'store_id'), MAX(store_id)) FROM stores for a SERIAL column. Do this after every bulk load with explicit keys. MySQL's AUTO_INCREMENT and SQL Server's IDENTITY behave differently: an explicit value higher than the counter moves the counter past it, so this collision is mostly a PostgreSQL and Oracle problem. In SQL Server, explicit values need SET IDENTITY_INSERT t ON, its equivalent of OVERRIDING SYSTEM VALUE. It's a common source of "duplicate key" errors after restoring or migrating data, and one reason to prefer GENERATED ALWAYS.
Sequences
An identity column is backed by a sequence, a database object that hands out numbers. Sequences can also be created and used directly:
-- A sequence is a separate object that hands out numbers
CREATE SEQUENCE invoice_no START WITH 1000 INCREMENT BY 1;
SELECT nextval('invoice_no') AS first, nextval('invoice_no') AS second;
SELECT currval('invoice_no') AS last_in_this_session;
-- One sequence can number rows in several tables: a single series of invoice numbers
CREATE TABLE shop_invoices (invoice_no BIGINT PRIMARY KEY DEFAULT nextval('invoice_no'), amount DECIMAL(10, 2));
CREATE TABLE online_invoices (invoice_no BIGINT PRIMARY KEY DEFAULT nextval('invoice_no'), amount DECIMAL(10, 2));
INSERT INTO shop_invoices (amount) VALUES (54.00);
INSERT INTO online_invoices (amount) VALUES (249.99);
INSERT INTO shop_invoices (amount) VALUES (16.00);
SELECT 'shop' AS source, invoice_no, 'INV-' || lpad(invoice_no::text, 6, '0') AS code FROM shop_invoices
UNION ALL
SELECT 'online', invoice_no, 'INV-' || lpad(invoice_no::text, 6, '0') FROM online_invoices
ORDER BY invoice_no;
first | second
-------+--------
1000 | 1001
(1 row)
last_in_this_session
----------------------
1001
(1 row)
source | invoice_no | code
--------+------------+------------
shop | 1002 | INV-001002
online | 1003 | INV-001003
shop | 1004 | INV-001004
(3 rows)
nextval('seq')returns the next value and advances the sequence. Each call gets a different value, even in concurrent sessions.currval('seq')returns the value most recently obtained bynextvalin this session. It's an error to call it beforenextval.CREATE SEQUENCEoptions set the start, increment, minimum and maximum values, whether it cycles, and how many values each session caches for speed.
A standalone sequence is useful when one series of numbers spans several tables. Here, shop and online invoices share one series, so an invoice number identifies an invoice whichever table it's in. A key used for display can be formatted from the number when it's shown, as with 'INV-' || lpad(...), rather than stored as text.
SQL Server 2012+, Oracle and Db2 support standard sequences, with NEXT VALUE FOR seq in SQL Server and seq.NEXTVAL in Oracle. MySQL has no sequences: use AUTO_INCREMENT, or a counter table.
UUIDs
A UUID (universally unique identifier) is a 128-bit value, written as 32 hexadecimal digits in five groups, such as 019a8c4e-6a00-7c3d-8f1e-2b4a6c8d0e1f. They can be generated by any process, on any machine, without asking the database, and two independently generated UUIDs will practically never collide.
-- UUIDs: 128-bit identifiers that can be generated anywhere without coordination
CREATE TABLE devices (
device_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
label TEXT NOT NULL
);
INSERT INTO devices (label) VALUES ('till 1'), ('till 2'), ('scanner');
-- The values are random, so look at their properties rather than the values themselves
SELECT COUNT(*) AS devices,
COUNT(DISTINCT device_id) AS distinct_ids,
MIN(length(device_id::text)) AS text_length,
MIN(uuid_extract_version(device_id)) AS version,
pg_column_size(MIN(device_id::text)::uuid) AS bytes_as_uuid
FROM devices;
-- A version 7 UUID begins with a 48-bit Unix timestamp in milliseconds, so newer values sort later
SELECT u AS uuid_v7,
uuid_extract_version(u) AS version,
to_timestamp(('x' || substr(replace(u::text, '-', ''), 1, 12))::bit(48)::bigint / 1000.0)
AT TIME ZONE 'UTC' AS created_at_utc
FROM (VALUES ('019a8c4e-6a00-7c3d-8f1e-2b4a6c8d0e1f'::uuid),
('019a8c4e-6a01-7aa0-9b2c-000000000000'::uuid)) AS t(u)
ORDER BY u;
devices | distinct_ids | text_length | version | bytes_as_uuid
---------+--------------+-------------+---------+---------------
3 | 3 | 36 | 4 | 16
(1 row)
uuid_v7 | version | created_at_utc
--------------------------------------+---------+-------------------------
019a8c4e-6a00-7c3d-8f1e-2b4a6c8d0e1f | 7 | 2025-11-16 10:55:40.544
019a8c4e-6a01-7aa0-9b2c-000000000000 | 7 | 2025-11-16 10:55:40.545
(2 rows)
gen_random_uuid()generates a version 4 UUID: 122 random bits. The query shows its properties rather than the values, which differ on every run: each is unique, 36 characters as text, and stored in 16 bytes by theuuidtype. Storing UUIDs as text instead takes 36 bytes or more and compares more slowly.- A version 7 UUID (standardised in RFC 9562, 2024) starts with a 48-bit timestamp in milliseconds, followed by random bits. The query decodes that timestamp from two values generated a millisecond apart. A UUID from a later millisecond therefore sorts after an earlier one (PostgreSQL's
uuidv7()also keeps values from one session increasing within a millisecond), so they sort roughly in creation order, like an identity column, while still being generable anywhere. PostgreSQL 18 addeduuidv7()to generate them, anduuid_extract_timestampreads the time from them.
Equivalents: MySQL's UUID() generates version 1, and UUID_TO_BIN(UUID(), 1) stores it in 16 bytes with the time bits reordered for better locality. SQL Server has NEWID(), random, and NEWSEQUENTIALID(), increasing, with the uniqueidentifier type. Oracle has SYS_GUID(), which returns 16 raw bytes. SQLite has no UUID type: store them as 16-byte blobs or text.
Integers or UUIDs?

Both are good choices, for different reasons:
| Identity / sequence | UUID v4 | UUID v7 | |
|---|---|---|---|
| size | 4 or 8 bytes | 16 bytes | 16 bytes |
| generated | by the database | anywhere | anywhere |
| order | increasing | random | increasing (by time) |
| index inserts | append at the end | scattered | append at the end |
| reveals | row count, creation order | nothing | creation time |
| merging data from several databases | collisions | no collisions | no collisions |
Points to weigh:
- Index locality. A B-tree index (article 55) on increasing keys receives every new key in its rightmost page, which stays in memory. Random version 4 UUIDs land in a random page each time, so a large table's inserts touch pages all over the index, causing more page splits, cache misses and write-ahead log. On big, write-heavy tables this is measurable. Version 7 UUIDs avoid it.
- Generation without the database. UUIDs can be created by clients, offline devices or several services before the row is ever inserted, and merged later without renumbering. Integers need a round trip to the database, or a coordinated scheme.
- Exposure. An integer key in a URL,
/orders/1042, tells outsiders how many orders exist and invites guessing neighbouring IDs. A UUID doesn't, although access control, not unguessable IDs, is what must protect data. A version 7 UUID does reveal when the row was created. - Size. 16 bytes per key, repeated in every foreign key and index, adds up on very large tables, while a
BIGINTtakes 8.
A common, balanced design is a BIGINT identity primary key for joins and storage, plus a UUID column with a unique index for use in URLs and APIs. If you use UUIDs as the primary key, prefer version 7. And use BIGINT rather than INTEGER for identity keys on tables that might grow large: a 4-byte integer runs out at about 2.1 billion, and changing the type of a busy primary key later is painful.
What's current
- PostgreSQL 18 added
uuidv7(), withuuidv4()as an alias forgen_random_uuid(), and extendeduuid_extract_timestampto version 7 UUIDs. - PostgreSQL 17 added
uuid_extract_versionanduuid_extract_timestamp. - RFC 9562 (2024) replaced RFC 4122 and standardised UUID versions 6, 7 and 8.
- MySQL 9 still has no built-in version 7 generator, so applications generate version 7 UUIDs themselves.
Common questions
Why are there gaps in my IDs? Rolled-back and failed inserts, deleted rows, cached values lost at restart, and upserts all use up numbers. That's normal and harmless for surrogate keys.
How do I get the ID of the row I just inserted?
INSERT ... RETURNING id in PostgreSQL, SQLite and Oracle, OUTPUT inserted.id or SCOPE_IDENTITY() in SQL Server, LAST_INSERT_ID() in MySQL. Never SELECT MAX(id).
Why do I get "duplicate key" errors on an identity column? Rows were inserted with explicit keys that the generator didn't know about. Restart it above the highest key.
ALWAYS or BY DEFAULT?
ALWAYS, unless the application must supply keys. It prevents accidental manual keys, and OVERRIDING SYSTEM VALUE still allows deliberate ones.
Should I use UUIDs as primary keys?
They're a good choice when keys must be generated outside the database or must not be guessable. Prefer version 7 for index performance, and store them in a native uuid type.
How do I make gapless invoice numbers? Not with a sequence or identity column. Increment a counter row in the same transaction as the insert.
Summary
- Identity columns generate increasing keys.
GENERATED ALWAYSrejects manual keys unlessOVERRIDING SYSTEM VALUEis used.BY DEFAULTaccepts them. RETURNING,OUTPUT,LAST_INSERT_ID()andSCOPE_IDENTITY()give the new key safely.MAX(id)doesn't.- Generated numbers are unique but not gapless. Use a counter row for gapless business numbers.
- Explicit keys don't move the generator: restart it after loading data.
- Sequences are standalone generators, with
nextvalandcurrval, and can be shared between tables. - UUIDs are 128-bit keys that can be generated anywhere. Version 4 is random, and version 7 is time-ordered and index-friendly.
- Choose integers for compactness and simplicity, and UUIDs for distributed generation and unguessable IDs. Use
BIGINTfor large tables.
Practice questions
Write an INSERT that adds a ticket with the subject 'Lantern flickers' and returns the new ticket_id.
Answer
INSERT INTO tickets (subject)
VALUES ('Lantern flickers')
RETURNING ticket_id;
A table's identity column has values 1 to 5. Three inserts follow: one commits, one is rolled back, and one commits. What IDs do the committed rows get?
Answer
6 and 8. The rolled-back insert took 7, and it isn't reused.
After loading rows with explicit IDs up to 500 into a GENERATED BY DEFAULT column, the next normal insert fails with a duplicate key error. Why, and what's the fix?
Answer
The explicit values didn't advance the generator, which still starts at 1. Restart it above the highest key: ALTER TABLE t ALTER COLUMN id RESTART WITH 501.
Give one advantage and one disadvantage of random version 4 UUID primary keys compared with BIGINT identity keys.
Answer
Advantage: they can be generated anywhere without the database, and they don't reveal row counts or invite guessing. Disadvantage: they're twice the size, and random values scatter inserts across the index, which slows writes on large tables. Version 7 UUIDs keep the first advantage and remove the index problem.
Previous: Changing Tables: ALTER TABLE, DROP and Foreign Key Actions

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.