Sub topic 3
Stored generated columns in practice
This chapter assumes you can write CREATE TABLE, INSERT, UPDATE and SELECT, and that you know the common PostgreSQL types (text, integer, numeric, timestamptz). You should also know what an index is. The previous chapter covered the syntax. Here you will use stored generated columns on realistic tables, inspect them in the catalog, and learn what they cost and where they surprise people.
What "stored" means
A stored generated column is a real column. PostgreSQL evaluates its expression when a row is written and saves the result in the row, next to the other column values. A read does no computation. The database simply returns the saved value.
The cost therefore falls on writes and on disk space. Every insert evaluates the expression. Every update that changes a column the expression depends on evaluates it again. The result takes as much space as an ordinary column of the same type.
The declaration has this form:
column_name data_type GENERATED ALWAYS AS (expression) STOREDThe data type is required, and the expression can use only columns of the same row.
A worked example: order line totals
Money calculations are a common reason to use generated columns. A line total should always agree with quantity, price and discount, and no application should be able to store a different value.
CREATE TABLE order_lines (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
quantity integer NOT NULL CHECK (quantity > 0),
unit_price numeric(10,2) NOT NULL,
discount_pct numeric(5,2) NOT NULL DEFAULT 0,
line_total numeric(12,2) GENERATED ALWAYS AS (
round(quantity * unit_price * (1 - discount_pct / 100), 2)
) STORED
);
INSERT INTO order_lines (quantity, unit_price, discount_pct)
VALUES (3, 19.99, 10),
(1, 5.00, 0)
RETURNING id, line_total;The RETURNING clause shows the computed values: 53.97 for the first row and 5.00 for the second. Now change the quantity:
UPDATE order_lines SET quantity = 4 WHERE id = 1 RETURNING line_total;The result is 71.96. You did not mention line_total in the UPDATE, and PostgreSQL still recomputed it. An application that forgets to update the total cannot leave it stale.
The expression uses round(numeric, integer) and ordinary arithmetic, and both are immutable. The immutability rule has its own chapter, so here is the short version. The expression must give the same output for the same inputs, always, because PostgreSQL stores the result and never checks it again.
The write path
The diagram shows where the computation happens when a row is written.
One consequence follows from this order. A BEFORE row trigger runs before the generation step, so it sees the old or NULL value of a generated column, not the new one. If a trigger needs the final value, use an AFTER trigger, or compute the value in the trigger from the base columns.
Reading the definition from the catalog
You will often need to find out which columns of an unfamiliar table are generated. Two places answer that.
SELECT column_name, is_generated, generation_expression
FROM information_schema.columns
WHERE table_name = 'order_lines'
ORDER BY ordinal_position;The is_generated column shows ALWAYS for generated columns and NEVER for the rest. The generation_expression column holds the expression text. The system catalog pg_attribute has the same information in its attgenerated column:
SELECT attname, attgenerated
FROM pg_attribute
WHERE attrelid = 'order_lines'::regclass
AND attnum > 0
AND NOT attisdropped;The value s means stored. In PostgreSQL 18 and later, v means virtual. A space means the column is not generated. In psql, \d order_lines also prints the expression in the column's default section as generated always as (...) stored.
Typical uses
Stored generated columns fit best when a value is derived from the same row and is read much more often than written.
Full-text search vectors
Keeping a tsvector column up to date used to require a trigger. A generated column does the same job declaratively:
CREATE TABLE articles (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
body text NOT NULL,
search tsvector GENERATED ALWAYS AS (
to_tsvector('english', title || ' ' || body)
) STORED
);
CREATE INDEX articles_search_idx ON articles USING gin (search);
INSERT INTO articles (title, body)
VALUES ('Generated columns', 'PostgreSQL computes these from other columns.');
SELECT id, title
FROM articles
WHERE search @@ websearch_to_tsquery('english', 'computes columns');The expression passes the text search configuration 'english' as a constant. The one-argument form of to_tsvector depends on the default_text_search_config setting, so it is not immutable and PostgreSQL rejects it here. Storing the vector is what makes the GIN index practical. The text is parsed once, at write time, not on every query.
Normalized keys
You can store a normalized copy of a value and enforce uniqueness on it:
CREATE TABLE accounts (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
email_norm text GENERATED ALWAYS AS (lower(btrim(email))) STORED UNIQUE
);
INSERT INTO accounts (email) VALUES ('[email protected] ');
-- Fails with a unique violation on email_norm:
INSERT INTO accounts (email) VALUES ('[email protected]');The unique constraint applies to the generated value, so the two spellings count as the same key. An expression index gives the same effect. The generated column has the advantage that email_norm is visible in queries and in SELECT *.
Other common uses
- Unit conversions, such as storing both
weight_gandweight_kg. - Flattening a field from a
jsonbcolumn, such as(payload ->> 'status'), so you can filter and index it like a normal column. - Rounded or bucketed values used for grouping, such as
date_truncon atimestamp(nottimestamptz, which is not immutable).
Constraints on a stored generated column
A generated column accepts NOT NULL and CHECK constraints, and it can take part in indexes, including unique indexes, as shown above. The check runs on the computed value:
ALTER TABLE order_lines
ADD CONSTRAINT line_total_not_negative CHECK (line_total >= 0);If a write would produce a value that fails the check, the whole statement fails. This is a useful way to validate a derived value.
A generated column cannot have a DEFAULT, because the expression already plays that role. It also cannot be an identity column, and its expression cannot reference another generated column.
Cost model
The table below summarizes what you pay for a stored generated column.
| Aspect | Effect |
|---|---|
| Disk space | Same as an ordinary column of that type, in the table and in any index on it |
| `INSERT` | Expression evaluated once per row |
| `UPDATE` | Expression evaluated again when a column it depends on changes |
| `SELECT` | No computation, the saved value is read |
| Indexing | Works like any column, since the value exists on disk |
Wide results such as tsvector or large text values can add noticeable size. PostgreSQL may move large values out of line (TOAST), as it does for any column. If the expression is expensive and rows are updated often, measure the write cost before committing to it.
Adding a stored column to an existing table
Adding a stored generated column is not a cheap metadata change:
ALTER TABLE order_lines
ADD COLUMN line_total_cents bigint
GENERATED ALWAYS AS ((line_total * 100)::bigint) STORED;PostgreSQL must compute the value for every existing row, so it rewrites the whole table. During the rewrite the command holds an ACCESS EXCLUSIVE lock, which blocks reads and writes. On a large production table, plan a maintenance window or test the duration on a copy first. The expression above refers to line_total, an ordinary stored column of the table. It is not generated by an expression that would make this a reference to another generated column, so wait: line_total is itself generated, and this statement fails. The rule is that a generated column cannot reference another generated column. To get cents, repeat the full expression using only base columns.
The altering chapter covers dropping the expression, and changing it, in detail. For now, remember that ALTER TABLE ... ALTER COLUMN ... DROP EXPRESSION keeps the values and turns the column into an ordinary one.
Things that surprise people
- You cannot write to it. An
INSERTorUPDATEthat supplies any value other thanDEFAULTraises an error. Application code that buildsINSERTstatements from every column of a table, including generated ones, will fail. Skip the generated columns or useDEFAULT. SELECT *includes it. The column appears in results like any other. ORMs that map every column to a writable field need to mark it read-only.- Some common functions are rejected.
concat()andconcat_ws()are declared stable, not immutable, so they cannot appear in the expression. Use||withcoalescefor nullable parts, as incoalesce(first_name, '') || ' ' || coalesce(last_name, ''). NULLpropagates. With||, aNULLinput makes the whole resultNULL. In a table with nullable base columns, decide whether that is what you want.- Backups store definitions, not values.
pg_dumpwrites the generation expression, and PostgreSQL recomputes the values on restore. A dump therefore stays valid even if you later change the expression on the live table. - Logical replication does not carry the column by default. The subscriber computes the value itself if its own column is generated. The limitations chapter returns to this.
Summary of the working model
A stored generated column is a normal column whose value PostgreSQL fills in for you. You read it freely, index it, and constrain it. You never write to it. You pay in disk space and write time, and you pay a table rewrite when you add one to a table that already has rows.
Exercise
A table invoices has net numeric(12,2) NOT NULL and tax_rate numeric(4,3) NOT NULL. Write a stored generated column gross equal to net plus tax, rounded to two decimals. Then say what happens to gross when you run UPDATE invoices SET tax_rate = 0.200 WHERE id = 7;, and what happens if you run UPDATE invoices SET gross = 0 WHERE id = 7;.
Show answer
Add it with gross numeric(12,2) GENERATED ALWAYS AS (round(net * (1 + tax_rate), 2)) STORED. The first UPDATE changes a column the expression depends on, so PostgreSQL recomputes and stores a new gross for row 7 without you mentioning it. The second UPDATE fails with an error, because only DEFAULT may be assigned to a generated column.
Exercise
You run ALTER TABLE big_table ADD COLUMN tag text GENERATED ALWAYS AS (lower(name)) STORED; on a table with 200 million rows during business hours. What is the problem, and what should you do first?
Show answer
PostgreSQL has to compute the value for every existing row, so it rewrites the whole table while holding an ACCESS EXCLUSIVE lock, which blocks reads and writes for the duration. First measure the time on a copy of the table, then schedule a maintenance window. Alternatively, consider an expression index on lower(name) if you only need fast lookups, since an index can be built with CREATE INDEX CONCURRENTLY without blocking writes.