Sub topic 11
Limitations and replication notes
This chapter collects the restrictions on generated columns and explains how they behave under replication, backup and restore. It assumes you know stored and virtual columns from the earlier chapters, the immutability rule, and basic publish/subscribe terms. Version notes use PostgreSQL 12 (stored columns added) and PostgreSQL 18 (virtual columns added).
Restrictions on the generation expression
The expression is evaluated for one row at a time, so it can only look at that row. These rules apply to both kinds of generated column:
- It can call only immutable functions.
- It cannot contain a subquery.
- It cannot reference another table, an aggregate, a window function, or a set-returning function.
- It cannot reference a system column, except
tableoid. - It cannot reference another generated column.
The last rule surprises people most, because a chain of derived values feels natural.
CREATE TABLE chained (
a integer,
b integer GENERATED ALWAYS AS (a * 2) STORED,
c integer GENERATED ALWAYS AS (b + 1) STORED
);
-- ERROR: cannot use generated column "b" in column generation expression
-- DETAIL: A generated column cannot reference another generated column.The fix is to repeat the base computation in the second expression:
CREATE TABLE chained (
a integer,
b integer GENERATED ALWAYS AS (a * 2) STORED,
c integer GENERATED ALWAYS AS (a * 2 + 1) STORED
);A subquery fails in the same way:
CREATE TABLE orders_bad (
id integer PRIMARY KEY,
customer_id integer,
customer_name text GENERATED ALWAYS AS (
(SELECT name FROM customers WHERE customers.id = customer_id)
) STORED
);
-- ERROR: cannot use subquery in column generation expressionIf a value depends on another table, a generated column cannot provide it. See the final chapter for views and triggers.
Restrictions on the column definition
A generated column differs from an ordinary column in several ways that affect your DDL.
- It cannot have a
DEFAULTor an identity definition. The expression is already the default. - You cannot write to it, except to set it to
DEFAULT. - It cannot be part of a partition key.
- Its type is fixed by the declaration. The expression result must be assignable to that type.
CREATE TABLE both (
a integer,
b integer DEFAULT 0 GENERATED ALWAYS AS (a + 1) STORED
);
-- ERROR: both default and generation expression specified for column "b" of table "both"Constraints and keys
Stored generated columns can take NOT NULL, CHECK, UNIQUE and primary key constraints. A stored generated column can also be part of a foreign key, with one limit. Because you cannot write to the column directly, the referential actions that would write to it are rejected. These are ON UPDATE CASCADE, ON UPDATE SET NULL, ON UPDATE SET DEFAULT, ON DELETE SET NULL and ON DELETE SET DEFAULT. NO ACTION, RESTRICT and ON DELETE CASCADE remain available.
Constraints are checked against the computed value. A CHECK on a generated column therefore fires when the base columns change, even though the UPDATE never named the generated column.
Virtual column restrictions (PostgreSQL 18)
A virtual column holds no data, so anything that needs stored data is unavailable. The table summarizes the differences.
| Capability | Stored | Virtual (PostgreSQL 18) |
|---|---|---|
| Plain index or expression index | Yes | No |
| Primary key or unique constraint | Yes | No |
| Foreign key | Yes, with the action limits above | No |
| Partition key | No | No |
| User-defined functions or types in the expression | Yes, if immutable | No, built-in only |
| Table rewrite when added | Yes | No |
| Logical replication | Yes, with a publication setting | No |
Check the release notes for your minor version. The built-in-only rule for virtual columns is a first-release restriction that later versions may relax.
Triggers
Generated columns are computed after BEFORE row triggers run. Two consequences follow:
- Inside a
BEFOREtrigger, the generated columns ofNEWdo not yet hold the final value. A trigger that readsNEW.full_namesees nothing useful. - A
BEFOREtrigger can change the base columns, and the generated column then reflects those changes.
If your trigger logic needs the computed value, use an AFTER trigger. If the trigger only needs to adjust inputs, a BEFORE trigger is fine.
CREATE FUNCTION log_full_name() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE 'full_name is %', NEW.full_name;
RETURN NULL;
END;
$$;
CREATE TRIGGER people_after_insert
AFTER INSERT ON people
FOR EACH ROW EXECUTE FUNCTION log_full_name();With the people table from earlier chapters, an insert of Ada Lovelace prints full_name is Ada Lovelace. Changing the trigger to BEFORE INSERT would print an empty value.
Inheritance and partitioning
A generated column cannot be a partition key, so you cannot partition by a derived value directly. Partition by the base column, or store the derived value in an ordinary column that a trigger or the application maintains.
With table inheritance, a column that is generated in the parent must also be generated in the child. Since PostgreSQL 16 the child may use a different expression. The child's own expression is the one that gets evaluated, so queries through the parent can return values computed by different formulas. Keep the expressions the same unless you want that behavior.
Replication and backup
The three mechanisms below handle generated columns differently. Physical replication and dump/restore need no action from you. Logical replication needs a decision.
Physical (streaming) replication
Physical replication ships WAL, which contains the exact changes to table pages. Stored generated values are part of those pages, so a standby holds identical data and does not recompute anything. Virtual columns have nothing to ship because they take no storage.
Logical replication
Logical replication sends row changes decoded from WAL, and the default output plugin has historically skipped generated columns:
- In PostgreSQL 17 and earlier, generated columns are never published, even if you list them in a column list.
- In PostgreSQL 18, you can publish stored generated columns. Set
publish_generated_columns = storedon the publication, or name the column in a publication column list. The default isnone. - Virtual generated columns cannot be published in any version.
-- On the publisher (PostgreSQL 18)
CREATE PUBLICATION pub_people
FOR TABLE people
WITH (publish_generated_columns = stored);The subscriber's table decides what happens to the received value. If the matching subscriber column is an ordinary column, it receives the publisher's value. If it is itself a generated column, the incoming value is ignored and the subscriber computes its own.
-- On the subscriber: ordinary column receives the published value
CREATE TABLE people (
id integer PRIMARY KEY,
first_name text NOT NULL,
last_name text NOT NULL,
full_name text
);
CREATE SUBSCRIPTION sub_people
CONNECTION 'host=publisher.example dbname=app user=repl'
PUBLICATION pub_people;The table definition above differs from the publisher's: id is a plain integer here, because the subscriber must accept explicit ids from the publisher.
The decision path for a generated column under logical replication looks like this:
Choosing between publishing and recomputing
You have two reasonable designs.
- Publish the stored value into an ordinary subscriber column. The subscriber sees exactly what the publisher computed. This needs PostgreSQL 18 on the publisher.
- Publish only the base columns and declare the same generated column on the subscriber. This works on every version that supports stored columns.
The second design has a hidden risk. The subscriber computes the value with its own software. An expression that is immutable on each server can still give different results across servers. Text functions that depend on the collation or on the operating system's locale library are the usual cause. If the subscriber differs, the same base data yields different derived values, and no error reports it. When exact agreement matters, publish the value or compare derived columns with a periodic checksum query.
Dump and restore
pg_dump does not write stored generated values into its data section. On restore the server recomputes them as rows load. Two things follow:
- Restoring into a server where an expression's behavior has changed produces different derived values than the original. This is the same collation risk as above.
- A large restore pays the computation cost once per row, in addition to index builds.
Because you cannot supply values for a generated column, a COPY into the table must leave the generated column out of its column list.
Operational notes
- Adding a stored generated column to an existing table rewrites the whole table under an
ACCESS EXCLUSIVElock. Plan it as a maintenance operation on large tables. - Updating a base column recalculates every stored generated column that depends on it. A wide table with several expensive expressions makes each update more costly, and the extra index entries add to that.
- Dropping the expression with
ALTER COLUMN ... DROP EXPRESSIONis a quick way out of a restriction. The column keeps its current values and becomes ordinary, so you can then publish it under older versions, partition by it, or write to it.
Summary of when a limit forces a different design
| Need | Generated column fits? | Typical alternative |
|---|---|---|
| Value from another table | No, subqueries are not allowed | Trigger, or a view with a join |
| Derived value that depends on another derived value | Only by repeating the base expression | View layered over the table |
| Partition by a derived value | No | Partition on the base column |
| Replicate the derived value on PostgreSQL 17 or earlier | No | Same definition on the subscriber, or an ordinary column maintained by a trigger |
| Index a virtual column | No | Expression index on the base expression |
Exercise
A publisher on PostgreSQL 17 has a stored generated column total defined as price * quantity. The subscriber table has total as an ordinary numeric column. After logical replication starts, what does the subscriber hold in total, and what are two ways to fix it?
Show answer
The subscriber's total is NULL (or its default), because PostgreSQL 17 never publishes generated columns. Fix 1: declare total on the subscriber as the same stored generated column, GENERATED ALWAYS AS (price * quantity) STORED, so it computes its own value. Fix 2: upgrade the publisher to PostgreSQL 18 and set publish_generated_columns = stored on the publication, so the published value is stored in the ordinary column.
Exercise
Why does CREATE TABLE t (a int, b int GENERATED ALWAYS AS (a + 1) STORED, c int GENERATED ALWAYS AS (b * 2) STORED) fail, and how do you write c so the table can be created?
Show answer
A generation expression cannot reference another generated column, and c references b. Write c in terms of the base column: c int GENERATED ALWAYS AS ((a + 1) * 2) STORED.
Exercise
In a BEFORE INSERT row trigger on a table with a stored generated column, why is reading the generated column from NEW unreliable, and which trigger timing should you use instead?
Show answer
Generated columns are computed after BEFORE row triggers run, so NEW does not yet hold the final computed value. Use an AFTER trigger to read the computed value. A BEFORE trigger can still change the base columns, and the generated column will reflect that change.