Sub topic 10
Changing Generated Columns on an Existing Table
This chapter assumes you can define a stored generated column and know that it behaves as read-only. It also assumes you know what an ACCESS EXCLUSIVE lock is, at least that it blocks other sessions from reading and writing the table. The examples continue with the people table from earlier chapters. The version notes matter here because the available ALTER TABLE forms differ between PostgreSQL 12, 13, 17 and 18.
What you can change
PostgreSQL does not offer one command that does everything. Each change maps to a different form, and some changes have no direct form at all.
| Goal | Command | Since | Rewrites the table? |
|---|---|---|---|
| Add a stored generated column | `ADD COLUMN ... GENERATED ALWAYS AS (...) STORED` | 12 | Yes |
| Add a virtual generated column | `ADD COLUMN ... GENERATED ALWAYS AS (...) VIRTUAL` | 18 | No |
| Replace the expression | `ALTER COLUMN ... SET EXPRESSION AS (...)` | 17 | Yes for stored, no for virtual |
| Turn a stored column into an ordinary column | `ALTER COLUMN ... DROP EXPRESSION` | 13 | No |
| Turn an ordinary column into a generated one | No direct command. Add a new column, drop the old one, rename. | Yes | |
| Remove the column | `DROP COLUMN` | all | No |
A table rewrite means PostgreSQL builds a new copy of the table's data and swaps it in. The rewrite holds an ACCESS EXCLUSIVE lock for its whole duration, so reads and writes on the table wait.
Adding a generated column
Adding a stored generated column to a table that already has rows forces PostgreSQL to compute the value for every existing row. It does this by rewriting the table.
ALTER TABLE people
ADD COLUMN initials text
GENERATED ALWAYS AS (left(first_name, 1) || left(last_name, 1)) STORED;
SELECT first_name, last_name, initials FROM people;On a table with a few thousand rows this takes milliseconds. On a table with hundreds of millions of rows it can take minutes, during which every query against the table is blocked. The same applies to any indexes on the table, because a rewrite rebuilds them.
In PostgreSQL 18 you can avoid the rewrite by adding a virtual column, since nothing is stored:
ALTER TABLE people
ADD COLUMN name_length integer
GENERATED ALWAYS AS (length(first_name) + length(last_name)) VIRTUAL;In PostgreSQL 18, a generated column declared without STORED or VIRTUAL is virtual. In 17 and earlier, STORED is mandatory. Write the keyword explicitly so the DDL means the same on every version.
The expression must follow the same rules as at table creation. It may use only immutable functions and only columns of the same table, and it may not reference another generated column. If it breaks a rule, the statement fails before any rewrite begins.
Inspecting what you have
Before changing anything, check which columns are generated and what their expressions are. The standard information_schema view shows this:
SELECT column_name, is_generated, generation_expression
FROM information_schema.columns
WHERE table_name = 'people'
ORDER BY ordinal_position;is_generated is ALWAYS for generated columns and NEVER for others. In psql, \d people shows the same information as generated always as (...) stored. For a script that must tell stored from virtual, read attgenerated in pg_attribute: s means stored, and in PostgreSQL 18 v means virtual.
Replacing the expression
Suppose the business now wants full_name as "Lovelace, Ada" instead of "Ada Lovelace". In PostgreSQL 17 and later, one statement does it:
ALTER TABLE people
ALTER COLUMN full_name
SET EXPRESSION AS (last_name || ', ' || first_name);For a stored column, PostgreSQL recomputes every row and rewrites the table, so the lock and time costs are the same as for adding a column. It also rebuilds indexes on the column, and it re-checks any constraints that involve it. If the new expression produces a value that violates a NOT NULL or CHECK constraint, the whole statement fails and the old expression stays in place. For a virtual column in 18, only the catalog entry changes, so the command is instant.
SET EXPRESSION works only on a column that is already generated. Running it on an ordinary column fails with an error saying the column is not a generated column.
Before PostgreSQL 17
There is no SET EXPRESSION. The workaround is the swap pattern described below: add a column with the new expression, drop the old column, and rename. Do all three steps in one transaction so no other session sees an intermediate state.
Dropping the expression
DROP EXPRESSION stops the column from being generated and keeps the values already in it:
ALTER TABLE people ALTER COLUMN full_name DROP EXPRESSION;No rewrite occurs, because the stored values are already on disk. The command needs only a brief lock. After it runs, full_name is an ordinary text column. It accepts direct writes, and changes to first_name or last_name no longer update it.
This is useful in three situations:
- You want to freeze historical values, for example an invoice total that must not change if a price column is corrected later.
- You want to take over maintenance of the column with a trigger or application code.
- You are preparing to replace the expression on PostgreSQL 16 or earlier.
Add IF EXISTS to make the command a no-op, with a notice, when the column is not generated. This helps migration scripts that may run twice.
ALTER TABLE people ALTER COLUMN full_name DROP EXPRESSION IF EXISTS;Dropping the expression of a stored column is the only direction with a direct command. It cannot be reversed in place, because no ADD GENERATED form exists for an existing column.
Converting an ordinary column into a generated one
Suppose full_name was a plain text column maintained by application code, and you now want PostgreSQL to own it. Use the swap pattern:
BEGIN;
ALTER TABLE people
ADD COLUMN full_name_new text
GENERATED ALWAYS AS (first_name || ' ' || last_name) STORED;
ALTER TABLE people DROP COLUMN full_name;
ALTER TABLE people RENAME COLUMN full_name_new TO full_name;
COMMIT;Check these points first:
- Do the old values match the new expression? Compare them before you start. Dropping the old column destroys the only copy of any values that differ.
``sql SELECT count(*) FROM people WHERE full_name IS DISTINCT FROM first_name || ' ' || last_name; ``
- What depended on the old column? Indexes on it disappear with
DROP COLUMN. Constraints, views, and foreign keys that reference it either block the drop or are removed withCASCADE. Recreate indexes and constraints on the new column afterwards. - Is the column order important? The renamed column goes at the end of the table. Code that uses
SELECT *and relies on position, orCOPYwithout a column list, will see a different order. - Is the table large? The
ADD COLUMNstep rewrites it, and the transaction holds the lock until commit.
Dependencies when you change the base columns
A generated column depends on the columns its expression uses. This shapes what you can do to those base columns.
- Dropping a base column fails with a message that other objects depend on it.
DROP COLUMN last_name CASCADEsucceeds, but it silently dropsfull_nametoo. Read the notices thatCASCADEprints. - Renaming a base column works. PostgreSQL stores the expression as a parsed tree that points at the column, so the expression follows the rename.
- Changing the type of a base column is rejected with an error saying the column is used by a generated column. Drop the expression or the generated column, change the type, and then restore it, ideally in one transaction.
The same dependency tracking applies to indexes and constraints on the generated column. Dropping the generated column removes them. Dropping only the expression keeps them, and they keep working on the now-ordinary values.
Choosing the migration path
Planning for large tables
The rewrite is the main operational risk. A few habits keep it manageable.
- Measure first. Copy the table to a staging database of similar size and time the statement. Rewrite time grows with table size and with the number of indexes.
- Set a lock timeout.
SET lock_timeout = '5s';makes theALTERfail fast if it cannot get the lock, instead of queueing. A queuedACCESS EXCLUSIVErequest also blocks every later query on the table, so a long-running transaction ahead of it can stall the whole application. - Use virtual columns where they fit. On PostgreSQL 18, a virtual column avoids the rewrite on add and on
SET EXPRESSION. The trade-off is a cost on every read, and a virtual column cannot be indexed. - Check disk space. A rewrite needs room for a full second copy of the table and its indexes until it commits.
- Avoid doing it in a long transaction. The swap pattern is atomic, but it holds its locks until commit, so keep everything else out of that transaction.
Common errors
cannot insert a non-DEFAULT value into column: after a migration, application code still writes to a column that is now generated. Remove the column from theINSERTandUPDATEcolumn lists, or useDEFAULT.column "x" is not a stored generated columnfromDROP EXPRESSION: the column is ordinary, or in some versions virtual. UseIF EXISTSin scripts that may rerun.generation expression is not immutableon add or onSET EXPRESSION: the new expression uses a function whose result depends on a session setting. Pick an immutable equivalent, or compute the value in a trigger instead.- Unexpected
NULLresults afterSET EXPRESSION: a base column is nullable and the new expression does not handle that.||returnsNULLif either side isNULL, so useconcat_ws(which is stable, not immutable, so check that it is accepted) orcoalesce, or declare the base columnsNOT NULL.
Exercise
A table orders(price numeric NOT NULL, quantity integer NOT NULL, total numeric) has a plain total column that the application fills in. You want PostgreSQL to compute it as price * quantity and keep an existing index on total. Which statements do you run, and what do you check first?
Show answer
First check that stored values match the formula: SELECT count(*) FROM orders WHERE total IS DISTINCT FROM price * quantity;. If the count is 0 or you accept losing the differences, run the swap in one transaction: ALTER TABLE orders ADD COLUMN total_new numeric GENERATED ALWAYS AS (price * quantity) STORED;, then ALTER TABLE orders DROP COLUMN total;, then ALTER TABLE orders RENAME COLUMN total_new TO total;. Dropping total removes its index, so recreate it afterwards with CREATE INDEX ... ON orders (total);. Use lock_timeout because the add step rewrites the table.
Exercise
On PostgreSQL 17, a stored generated column slug has an index and a CHECK constraint. You run ALTER TABLE articles ALTER COLUMN slug SET EXPRESSION AS (lower(title));. What happens to the table, the index, and the constraint, and what happens if some new value violates the constraint?
Show answer
PostgreSQL rewrites the table under an ACCESS EXCLUSIVE lock, recomputes slug for every row, and rebuilds the index. It re-checks the CHECK constraint against the new values. If any new value violates the constraint, the statement fails as a whole and the old expression and data remain.
Exercise
You run ALTER TABLE people ALTER COLUMN full_name DROP EXPRESSION;. Later, UPDATE people SET last_name = 'Byron' WHERE first_name = 'Ada'; runs. What does full_name contain for Ada, and can you restore the generated behavior in place?
Show answer
It still contains the value stored before the drop, for example 'Ada King', because the column is now ordinary and no longer follows last_name. You cannot restore generation in place. Use the swap pattern: add a new generated column, drop the old one, and rename.