Sub topic 5
GENERATED ALWAYS vs GENERATED BY DEFAULT
This chapter assumes you can write CREATE TABLE and INSERT statements, know what a primary key is, and know the integer types. It also assumes you have seen the basic GENERATED ... AS IDENTITY syntax from the previous chapter. Here you will learn the one choice that syntax asks you to make: who is allowed to supply the value of the ID.
The two modes
An identity column is attached to a sequence, an internal counter that hands out the next number. The word after GENERATED sets the rule for explicit values:
GENERATED ALWAYS AS IDENTITY: PostgreSQL is the only source of values. AnINSERTthat names the column with a value of its own is rejected.GENERATED BY DEFAULT AS IDENTITY: PostgreSQL supplies a value only when theINSERTleaves the column out or writesDEFAULT. An explicit value is accepted and stored.
In both modes the generated values come from the same kind of sequence. The difference is only in how the column treats values that arrive from outside.
GENERATED ALWAYS in practice
Start with a table that uses ALWAYS.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL
);
INSERT INTO orders (customer) VALUES ('Ada') RETURNING id;The insert leaves out id, so PostgreSQL calls the sequence and stores the result. Now try to choose the value yourself.
INSERT INTO orders (id, customer) VALUES (100, 'Grace');
-- ERROR: cannot insert a non-DEFAULT value into column "id"
INSERT INTO orders (id, customer)
OVERRIDING SYSTEM VALUE
VALUES (100, 'Grace');The first statement fails. The second succeeds because OVERRIDING SYSTEM VALUE tells PostgreSQL that you mean to bypass the rule for this one statement. The next chapter covers the OVERRIDING clauses in detail. For now, note that ALWAYS forces you to opt in explicitly each time.
Writing DEFAULT for the column is still allowed in ALWAYS mode, because it asks PostgreSQL to generate the value:
INSERT INTO orders (id, customer) VALUES (DEFAULT, 'Linus') RETURNING id;GENERATED BY DEFAULT in practice
With BY DEFAULT, explicit values just work. This example also sets sequence options, which a later chapter explains.
CREATE TABLE tickets (
id integer GENERATED BY DEFAULT AS IDENTITY (START WITH 1000 INCREMENT BY 10) PRIMARY KEY,
title text NOT NULL
);
INSERT INTO tickets (title) VALUES ('first'), ('second') RETURNING id;The two rows receive 1000 and 1010. Inserting a row with id = 5 would also succeed, with no extra clause.
The collision risk
That flexibility has a cost. The sequence does not know that someone inserted an explicit value, so it keeps counting from where it was. Suppose you insert id = 1020 by hand into tickets. When the sequence later reaches 1020, the generated value collides with the manual one.
INSERT INTO tickets (id, title) VALUES (1020, 'manual');
INSERT INTO tickets (title) VALUES ('generated'); -- gets 1020
-- ERROR: duplicate key value violates unique constraint "tickets_pkey"The primary key catches the duplicate, and the failed insert still uses up a sequence value, so a retry succeeds with 1030. Without the primary key, both rows would be stored with the same ID. This is why a primary key or unique constraint should always accompany an identity column: identity generates numbers but does not enforce uniqueness.
How the two modes compare
| Aspect | GENERATED ALWAYS | GENERATED BY DEFAULT |
|---|---|---|
| Insert without the column | Generated | Generated |
| Insert with `DEFAULT` | Generated | Generated |
| Insert with an explicit value | Error unless `OVERRIDING SYSTEM VALUE` | Accepted |
| Update the column to a new value | Error unless set to `DEFAULT` | Accepted |
| Protection against accidental collisions | Strong | Weak |
| Convenience for data loads and imports | Needs `OVERRIDING` | Direct |
The update row matters. In ALWAYS mode you cannot change an existing ID with UPDATE ... SET id = 7. That fits the idea of a surrogate key, which should never change.
Choosing a mode
Use GENERATED ALWAYS when the database should own the IDs. This is the better default for new application tables. Application code that tries to set an ID is almost certainly a bug, and ALWAYS turns that bug into an immediate error instead of a later collision.
Use GENERATED BY DEFAULT when you have a real reason to supply IDs:
- You load data that already has IDs, such as a migration from another system, and you want plain
INSERTorCOPYstatements to work. - You replicate or restore data that must keep its original keys.
- You migrate from
serial, whose columns accept explicit values.BY DEFAULTmatches that behavior, which is why the migration example later in this tutorial uses it. - Tools or ORMs you cannot change insert IDs explicitly.
If you are unsure, start with ALWAYS. Switching later is a one-line change, as shown below.
Switching modes
You can change the mode on an existing column without rewriting the table.
ALTER TABLE orders ALTER COLUMN id SET GENERATED BY DEFAULT;You can switch back the same way with SET GENERATED ALWAYS. Existing rows and the sequence's current position are not touched. Only the rule for future statements changes.
A common pattern is to switch to BY DEFAULT for a bulk load, then switch back to ALWAYS afterward. Remember to fix the sequence in between if the load included explicit IDs. A later chapter covers resynchronization.
Common errors
- Forgetting that
ALWAYSrejects explicit IDs. Import scripts and test fixtures that write IDs fail withcannot insert a non-DEFAULT value into column. Either addOVERRIDING SYSTEM VALUEor chooseBY DEFAULT. - Assuming
BY DEFAULTkeeps the sequence in sync. Explicit inserts do not advance the sequence. The collision appears later, often in production, when the counter reaches a manually inserted value. - Omitting the primary key. Neither mode creates a unique index. Always declare
PRIMARY KEYorUNIQUE. - Trying to update an
ALWAYSID.UPDATE orders SET id = 5fails. Update toDEFAULTonly if you want a fresh generated value, which you rarely do. - Expecting
ALWAYSto stop superusers or table owners. It is a rule on ordinary statements, andOVERRIDING SYSTEM VALUEbypasses it for anyone allowed to insert. Treat it as a guard against mistakes, not as a security control.
Summary
Both modes generate IDs from a sequence and both need a primary key for uniqueness. ALWAYS rejects explicit values unless you say OVERRIDING SYSTEM VALUE, which makes it the safer default. BY DEFAULT accepts explicit values, which suits data loads and migrations, but it leaves you responsible for keeping the sequence ahead of the stored IDs.
Exercise
A table invoices has id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY. A script inserts a row with id = 3 while the sequence is still at 1. Later the application inserts rows without an ID. What happens when the sequence reaches 3, and what mode change would have prevented the script from inserting that ID by accident?
Show answer
When the sequence generates 3, the insert fails with a duplicate key error on the primary key, because the sequence does not know about the manually inserted row. Declaring the column GENERATED ALWAYS would have made the script's insert fail with "cannot insert a non-DEFAULT value into column" unless it used OVERRIDING SYSTEM VALUE.
Exercise
You must load 50,000 rows from an old system into a GENERATED ALWAYS identity table and keep their original IDs. Name two ways to do it with plain inserts, and say what you must do afterward.
Show answer
Either add OVERRIDING SYSTEM VALUE to the INSERT statements, or temporarily run ALTER TABLE ... ALTER COLUMN id SET GENERATED BY DEFAULT and switch back to ALWAYS after the load. Afterward, move the sequence past the highest loaded ID, for example with setval(pg_get_serial_sequence('table', 'id'), max(id)), so future generated IDs do not collide with the loaded ones.