How to Use Generated Columns and Identity in PostgreSQL
Use generated columns for derived values and identity columns for keys: keep derivations consistent, index them, and avoid the wrong default.
On this page
Introduction
Two small schema features remove a lot of application code and a class of consistency bugs. Generated columns compute a value from other columns in the same row and keep it automatically in step, so a derived field cannot drift from its source. Identity columns produce surrogate keys with clearer semantics than the older serial type. Used deliberately, they move invariants from application code into the schema, where they cannot be bypassed.
This tutorial covers when to store versus compute a derived value, how to define a generated column and index it, how to choose identity generation behavior, and how to test that the database, not the application, enforces the derivation. The examples use PostgreSQL, which supports stored generated columns and standard identity columns.
Stored versus virtual, and when to derive
A generated column is defined by an expression over other columns of the same row. In PostgreSQL it is stored: the value is computed when the row is inserted or updated and saved on disk. That means it can be indexed and read at no computation cost, which is what you want for a frequently filtered derived value. A virtual column, computed at read time, costs nothing to store but cannot be indexed and is recomputed on every read; PostgreSQL does not currently store virtual columns, so the choice there is whether to generate at all or compute in a view.
Derive a value when it is a pure function of the same row and you query or index it. A search tsvector, a normalized form of an email, or a total computed from components are all good candidates. Do not generate values that depend on other rows or on mutable external state, because a generated column cannot reference them and the value would be wrong as soon as the other row changed. For those, use a trigger or recompute in a query.
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY,
email text NOT NULL,
email_lower text GENERATED ALWAYS AS (lower(email)) STORED,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX idx_users_email_lower ON users (email_lower);
Derive rather than duplicate
The value of a generated column is that the database keeps it consistent, so the application cannot forget to update it or update it with a different formula. Duplicating a derived value in application code, by computing it on insert and again on update, is the pattern generated columns replace. The fewer places that can compute a field, the fewer ways it can be wrong.
Keep the expression immutable. A generated column expression must not call a volatile function such as now() or random(), because the value would depend on when the row was touched and could not be reproduced. If you need a value that depends on time, store the input, such as the created_at timestamp, and derive from that stored value instead of from the clock.
Choose identity over serial
An identity column is the standard way to hand out surrogate keys. GENERATED ALWAYS AS IDENTITY forbids supplying a value in an ordinary insert, so the column cannot be set to an arbitrary value by a careless caller and must be overridden explicitly if you need to. GENERATED BY DEFAULT AS IDENTITY allows a caller to supply a value, which is useful for data migration and bulk import where the keys are known.
Prefer identity to serial for new tables. Serial is a legacy shorthand that creates a sequence and a default; identity expresses the intent directly and behaves more predictably across dump and restore and across tools that inspect the schema. If you must import rows with explicit keys, use BY DEFAULT and then reset the sequence so the next generated value is above the imported maximum, or the next insert collides with an imported key.
-- allow explicit ids for import, then align the sequence
CREATE TABLE legacy_users (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
name text NOT NULL
);
INSERT INTO legacy_users (id, name) VALUES (1000, 'imported');
SELECT setval(pg_get_serial_sequence('legacy_users', 'id'), (SELECT max(id) FROM legacy_users));
Index and query the generated value
Because a stored generated column is materialized, an index on it is used by the planner exactly like any other column. A functional index, an index on an expression, is the alternative when you do not want to store the value at all, but it stores the expression result in the index instead. Choose a generated column when several queries use the derived value, and a functional index when only the index needs it.
Filtering on the generated column, not on the raw column wrapped in the same function, is what lets the index apply. A query on lower(email) = $1 can use an index on lower(email) if the planner recognizes it, but a query on email_lower = $1 is unambiguous and cannot be mis-planned. Naming the generated column and querying it directly keeps the planner and the reader aligned.
Test derivation and insert semantics
Test that a generated column equals its formula for several rows, including edge inputs such as an email with mixed case. Test that an ALWAYS identity column rejects a supplied value and a DB DEFAULT one accepts it. Test that after an import with explicit ids, the next generated id does not collide. These tests pin the schema invariants so a later migration cannot quietly weaken them.
psql -d app <<'SQL'
INSERT INTO users (email) VALUES ('[email protected]');
SELECT email_lower FROM users WHERE email = '[email protected]'; -- expect [email protected]
INSERT INTO legacy_users (name) VALUES ('next');
SELECT max(id) > 1000 FROM legacy_users; -- expect t, no collision
SQL
Common pitfalls
Generating a value that depends on other rows or on the clock, duplicating a derived field in application code instead of generating it, using serial on new tables, importing explicit ids into an ALWAYS identity column, and forgetting to reset the sequence after a bulk import are the recurring mistakes. Pure-row derivations, identity columns, and sequence alignment address them.
Conclusion
Generated columns and identity columns move invariants into the schema. Derive pure-row values and index the stored result, keep expressions immutable, prefer identity to serial and choose its generation mode deliberately, and align the sequence after an explicit import. Self-check by asserting the derived value matches its formula and that identity generation behaves as configured. The database then enforces consistency the application cannot forget.
Sources: PostgreSQL: Generated columns, PostgreSQL: Identity columns, SQL standard: generated columns.
FAQ
- Stored or virtual generated column?
- A stored generated column is computed on write and saved, so it can be indexed and read cheaply. A virtual one is computed on read and cannot be indexed. In PostgreSQL, generated columns are stored; use them when you want to index or frequently read the derived value.
- Identity or serial?
- Identity is the standard-conformant replacement for serial. It gives clearer control over whether values are always generated or can be overridden, and it behaves more predictably across dump and restore. Use identity for new tables.
Report a problem with this articleOpens a pre-filled issue on GitHub.