Sub topic 4
What the Expression May Contain
This chapter covers the rules for the expression after GENERATED ALWAYS AS. It assumes you can write CREATE TABLE statements, know the common types (text, integer, numeric, timestamptz), and have seen the basic GENERATED ALWAYS AS (...) STORED syntax from the previous chapters.
The rule in one sentence
A generation expression is a pure function of the other columns in the same row. Given the same column values, it must always return the same result, and it must not look at anything outside that row.
PostgreSQL enforces this at CREATE TABLE or ALTER TABLE time. A rejected expression never creates a column that could later drift out of sync.
The restrictions fall into four groups:
- Every function and operator must be immutable.
- The expression may read only ordinary columns of its own table row.
- It may not read another generated column.
- Its result must convert to the column's type.
Virtual columns, added in PostgreSQL 18, have one extra restriction. It is covered near the end of the chapter.
Immutability
Every function in PostgreSQL carries a volatility label. The label is a promise about how the function behaves.
| Label | Meaning | Examples | Allowed in a generation expression? | Column | Column |
|---|---|---|---|---|---|
| `IMMUTABLE` | Same arguments always give the same result, forever | `lower(text)`, `abs`, ` | ` on text, `round(numeric, int)` | Yes | |
| `STABLE` | Same result within one statement, but may change between statements or sessions | `now()`, `current_setting()`, `to_char(timestamptz, text)` | No | ||
| `VOLATILE` | May return a different result on every call | `random()`, `clock_timestamp()`, `nextval()` | No |
The reason is simple. A stored value is computed once and then kept. If the function could give a different answer later, the stored value would disagree with a fresh evaluation, and the column would no longer mean "the expression applied to this row".
You can look up the label of any function in the system catalog:
SELECT p.proname,
pg_get_function_identity_arguments(p.oid) AS args,
CASE p.provolatile
WHEN 'i' THEN 'immutable'
WHEN 's' THEN 'stable'
WHEN 'v' THEN 'volatile'
END AS volatility
FROM pg_proc p
WHERE p.proname IN ('lower', 'now', 'random', 'to_char')
ORDER BY p.proname, args;to_char appears several times because it is overloaded. The timestamp variant and the timestamptz variant have different labels, and that difference matters in the next section.
A failing expression and its fix
Formatting a timestamptz as text depends on the session's TimeZone setting. The same instant can print as a different year around midnight on 31 December. That is why to_char(timestamptz, text) is stable, not immutable, and why this definition fails:
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
ts timestamptz NOT NULL,
year_text text GENERATED ALWAYS AS (to_char(ts, 'YYYY')) STORED
);
-- ERROR: generation expression is not immutableThe fix is to remove the dependency on the session time zone. Convert the value to a fixed zone first. AT TIME ZONE 'UTC' turns a timestamptz into a plain timestamp, and to_char(timestamp, text) is immutable:
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
ts timestamptz NOT NULL,
year_text text GENERATED ALWAYS AS (
to_char(ts AT TIME ZONE 'UTC', 'YYYY')
) STORED
);
INSERT INTO events (ts) VALUES ('2026-12-31 23:30:00-05');
SELECT year_text FROM events; -- 2027, because 23:30 at UTC-5 is 04:30 UTC on 1 JanuaryThe result is the UTC year, whatever time zone the session uses. If you want a different fixed zone, name it in the expression, for example 'Europe/Berlin'. The time zone is then part of the column's definition, not a session setting.
The same pattern applies to extract(year FROM ts) and date_trunc('day', ts) on a timestamptz. Both are stable. Convert to timestamp first, or use a date or timestamp column.
Only the current row
The expression may refer to ordinary columns of the same table. It cannot do any of these things:
- Contain a subquery, such as
(SELECT rate FROM tax_rates WHERE ...). - Refer to another table.
- Use an aggregate function, a window function, or a set-returning function.
- Read system columns, except
tableoid.
The restriction follows from the purpose of the feature. A value that depends on other rows or tables would need recomputation whenever those rows change, and PostgreSQL does not track that. If you need such behavior, see the alternatives chapter (views and triggers).
A useful pattern that stays inside the rules is full-text search. The two-argument to_tsvector(regconfig, text) is immutable because the language configuration is named explicitly. The one-argument form uses the default_text_search_config setting, so it is stable and would be rejected:
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', coalesce(title, '') || ' ' || coalesce(body, ''))
) STORED
);
INSERT INTO articles (title, body)
VALUES ('Generated columns', 'PostgreSQL computes these values for you.');
SELECT id FROM articles WHERE search @@ to_tsquery('english', 'compute');No chains of generated columns
A generation expression may not reference another generated column, even if that column is itself immutable and simple:
CREATE TABLE prices (
net numeric(10,2) NOT NULL,
vat numeric(10,2) GENERATED ALWAYS AS (net * 0.20) STORED,
gross numeric(10,2) GENERATED ALWAYS AS (net + vat) STORED
);
-- ERROR: cannot use generated column "vat" in column generation expression
-- DETAIL: A generated column cannot reference another generated column.Repeat the underlying expression in the second column instead:
CREATE TABLE prices (
net numeric(10,2) NOT NULL,
vat numeric(10,2) GENERATED ALWAYS AS (net * 0.20) STORED,
gross numeric(10,2) GENERATED ALWAYS AS (net + net * 0.20) STORED
);The duplication is a real cost, because the two formulas can drift apart when someone edits one. If you have several levels of derived values, a view that computes the later levels from the generated ones is often cleaner.
Your own functions
You can write your own function and use it in a generation expression, but it must be labeled IMMUTABLE:
CREATE FUNCTION normalize_sku(raw text) RETURNS text
LANGUAGE sql IMMUTABLE
AS $$ SELECT upper(regexp_replace(raw, '[^A-Za-z0-9]', '', 'g')) $$;
CREATE TABLE products (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku_raw text NOT NULL,
sku text GENERATED ALWAYS AS (normalize_sku(sku_raw)) STORED
);
INSERT INTO products (sku_raw) VALUES ('ab-12 / x');
SELECT sku FROM products; -- AB12XPostgreSQL checks only the label, not the function body. If you mark a function IMMUTABLE while it reads a table, a setting, or the clock, PostgreSQL accepts the column and you get silently wrong data. The responsibility is yours.
Two consequences follow:
- Changing the function later does not recompute existing rows.
CREATE OR REPLACE FUNCTION normalize_skuwith new logic leaves the old stored values in place. Rows written afterwards use the new logic, so the table now contains a mix. To realign it, drop and re-add the column, or rewrite the values in a controlled migration. - A dump and restore must create the function before the table.
pg_dumphandles this dependency order, but hand-written migration scripts must respect it too.
Result type and other column options
The expression's result is converted to the column's declared type, using an assignment cast. If no such cast exists, creation fails. Declare the type you want and make sure the expression produces something convertible. For example, a numeric(10,2) column rounds the expression result to two decimal places.
A generated column also cannot have a DEFAULT or an identity specification. DEFAULT and the generation expression would both describe where the value comes from, so PostgreSQL rejects the combination. A generated column may have NOT NULL and CHECK constraints. They are tested against the computed value.
Extra rule for virtual columns
From PostgreSQL 18 you can write VIRTUAL instead of STORED. The value is then computed when the column is read. Because the expression runs inside arbitrary queries, possibly by users who have no rights on the function, PostgreSQL 18 restricts virtual columns to built-in functions and built-in types. A user-defined function such as normalize_sku works in a STORED column but is rejected in a VIRTUAL one. All the other rules in this chapter apply to both kinds.
Deciding whether an expression is allowed
Common errors at a glance
| Symptom | Cause | Remedy |
|---|---|---|
| `generation expression is not immutable` | Stable or volatile function such as `now()`, `random()`, `to_char(timestamptz, ...)` | Use an immutable variant, or convert to a fixed zone first |
| `cannot use subquery in column generation expression` | Subquery or lookup in another table | Use a view, or a trigger that fills an ordinary column |
| `cannot use generated column "x" in column generation expression` | Chained generated columns | Repeat the base expression |
| `both default and generation expression specified` | `DEFAULT` combined with `GENERATED` | Remove one of them |
| Stored values disagree after editing a function | Mutable function body labeled `IMMUTABLE`, or the function was replaced | Rewrite the data, or drop and re-add the column |
Exercises
Exercise
Why does GENERATED ALWAYS AS (to_char(ts, 'YYYY')) STORED fail when ts is timestamptz, and how do you make it work?
Show answer
to_char(timestamptz, text) depends on the session TimeZone setting, so it is stable, not immutable. Convert to a fixed zone first: to_char(ts AT TIME ZONE 'UTC', 'YYYY'). This uses the immutable to_char(timestamp, text).
Exercise
A table has a integer, b integer GENERATED ALWAYS AS (a * 2) STORED. You want a third column equal to b + 1. What do you write, and why can't you write b + 1?
Show answer
Write c integer GENERATED ALWAYS AS (a * 2 + 1) STORED. A generation expression cannot reference another generated column, so b + 1 is rejected. The base expression has to be repeated.
Exercise
You mark a function IMMUTABLE and use it in a stored generated column. Later you change the function body with CREATE OR REPLACE FUNCTION. What happens to the rows already in the table, and what are your options?
Show answer
Existing rows keep the values computed by the old body. PostgreSQL does not recompute them. Rows written afterwards use the new body, so the table becomes inconsistent. To fix it, rewrite the column (for example drop it and add it again, which recomputes all rows) or run a controlled migration that rewrites the values.
Exercise
Which of these can appear in a generation expression? (a) lower(email) (b) now() (c) (SELECT max(id) FROM other) (d) to_tsvector('english', title)
Show answer
(a) and (d). lower on text and the two-argument to_tsvector are immutable. now() is stable, and a subquery is not allowed at all.