Sub topic 2
Defining a generated column
This chapter covers the syntax of a generated column, the rules that decide whether an expression is accepted, and how to check what PostgreSQL stored. It assumes you can write CREATE TABLE, INSERT, UPDATE and SELECT, know the common types (text, integer, numeric, timestamptz), and know what an index is. Later chapters cover write behavior, virtual columns and indexing in more detail.
What a generated column is
A generated column is a column whose value PostgreSQL computes from an expression over other columns in the same row. You declare the expression once in the table definition. The database then keeps the result consistent, so no application, trigger or batch job has to.
Without one, you have three options for a derived value such as a full name:
- Compute it in every query. Every reader has to repeat the formula correctly.
- Compute it in application code before writing. Any writer that skips this code, such as a script, a migration or a second service, can leave a wrong value.
- Maintain it with a trigger. This works, but you have to write and test the trigger function.
A generated column moves the formula into the schema, where it applies to every writer.
The syntax
The general form is a column name, a data type, and a generation clause:
column_name data_type GENERATED ALWAYS AS (expression) STORED| Part | Meaning |
|---|---|
| `column_name data_type` | An ordinary column definition. The type is mandatory. |
| `GENERATED ALWAYS` | The value always comes from the expression. You cannot choose it yourself. |
| `AS (expression)` | The formula. The parentheses are required. |
| `STORED` | PostgreSQL computes the value on write and saves it in the row on disk. |
The same GENERATED ALWAYS words appear in identity columns (GENERATED ALWAYS AS IDENTITY). The two features are separate. After AS, an opening parenthesis means a generated column, and the keyword IDENTITY means an identity column.
PostgreSQL 18 also accepts VIRTUAL in place of STORED. A virtual column takes no storage and is computed when it is read. Versions 12 through 17 accept only STORED, and the keyword cannot be left out there. In version 18, a generated column with neither keyword is virtual. Always write the keyword so the intent is clear on every version. Chapter 6 covers virtual columns in full.
A first example
This table derives full_name from two other columns:
CREATE TABLE people (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
first_name text NOT NULL,
last_name text NOT NULL,
full_name text GENERATED ALWAYS AS (first_name || ' ' || last_name) STORED
);
INSERT INTO people (first_name, last_name) VALUES ('Ada', 'Lovelace');
SELECT full_name FROM people;The INSERT lists only first_name and last_name. PostgreSQL evaluates first_name || ' ' || last_name for the new row and saves the result in full_name. The SELECT returns Ada Lovelace.
The data type and coercion
You must declare the column's type, and PostgreSQL does not infer it from the expression. If the expression's result type differs from the declared type, PostgreSQL applies an assignment cast, the same conversion it uses when you INSERT a value into that column. The next example relies on this:
CREATE TABLE line_items (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
unit_price numeric(10,2) NOT NULL,
quantity integer NOT NULL,
total numeric(12,2) GENERATED ALWAYS AS (unit_price * quantity) STORED
);
INSERT INTO line_items (unit_price, quantity) VALUES (19.99, 3);
SELECT unit_price, quantity, total FROM line_items;The expression multiplies a numeric by an integer, which produces a numeric. PostgreSQL then fits it to numeric(12,2), so total is 59.97. If the result cannot fit the declared type, the write fails with the same error a plain insert would give, for example numeric field overflow. The failure rolls back the whole statement.
You can also attach other column constraints to a generated column. NOT NULL and CHECK are allowed. A generated column cannot have a DEFAULT, because the expression already plays that role.
What the expression may contain
A generation expression is deliberately restricted, because PostgreSQL must be able to recompute it at any time and get the same answer from the same inputs. The rules are:
- It may refer only to other columns of the same table and row. It cannot use subqueries or columns of other tables.
- It may refer only to non-generated columns. One generated column cannot be built on another.
- It may call only immutable functions and operators. An immutable function always returns the same result for the same arguments.
- It cannot use system columns, apart from
tableoid.
Immutability in practice
Many familiar functions are not immutable. Volatile functions such as random() or clock_timestamp() can return different values on every call. Stable functions such as now() return the same value within one statement but can differ between statements. Some functions are stable only because they read a session setting, such as the time zone or locale. PostgreSQL rejects both kinds when you create the table:
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
);
-- Fails: the generation expression is not immutable,
-- because to_char on timestamptz depends on the session time zone.The error is ERROR: generation expression is not immutable. The same instant belongs to different calendar years in different time zones, so the result depends on a setting outside the row.
The fix is to remove the dependency by fixing the time zone in the expression:
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
);ts AT TIME ZONE 'UTC' is immutable and returns a plain timestamp, and to_char on a plain timestamp is immutable too. The year now means the year in UTC, which may differ from the year a user sees locally. Choose the time zone on purpose.
You can check a function's volatility in the system catalog before you rely on it:
SELECT proname, provolatile
FROM pg_proc
WHERE proname IN ('lower', 'now', 'random', 'to_char');In provolatile, i means immutable, s stable and v volatile. A function can have several overloads, one per argument type, so the query may return more than one to_char row with different values.
How user-defined functions fit in
You can call your own function in a generation expression only if it is declared IMMUTABLE. PostgreSQL trusts the label and does not verify the function body:
CREATE FUNCTION normalize_sku(s text) RETURNS text
LANGUAGE sql IMMUTABLE
AS $$ SELECT upper(btrim(s)) $$;
CREATE TABLE products (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
raw_sku text NOT NULL,
sku text GENERATED ALWAYS AS (normalize_sku(raw_sku)) STORED
);A function marked IMMUTABLE that actually reads a table or a setting will not be caught at creation time. If its behavior later changes, stored values can silently disagree with the new formula. Only mark a function immutable when it depends on nothing but its arguments.
Inspecting a generated column
Three places show what you defined.
In psql, \d line_items lists the column with generated always as (...) stored in the Default column.
The standard information_schema exposes the flag and the expression:
SELECT column_name, is_generated, generation_expression
FROM information_schema.columns
WHERE table_name = 'line_items'
ORDER BY ordinal_position;Generated columns show ALWAYS in is_generated, and other columns show NEVER. The generation_expression column holds the expression text as PostgreSQL stored it, which may be rewritten slightly (extra casts, added parentheses).
The system catalog pg_attribute has an attgenerated column. It holds s for a stored generated column, v for a virtual one (version 18 and later), and an empty string for an ordinary column:
SELECT attname, attgenerated
FROM pg_attribute
WHERE attrelid = 'line_items'::regclass
AND attnum > 0
AND NOT attisdropped;Common definition errors
| Symptom | Cause | Fix |
|---|---|---|
| `syntax error at or near "STORED"` or an error that a keyword is required | Missing parentheses around the expression, or `VIRTUAL` used on a version before 18 | Write `AS (expr) STORED`. Check your server version with `SHOW server_version;`. |
| `generation expression is not immutable` | The expression calls a stable or volatile function | Replace it with an immutable form, or fix the setting it depends on, as with `AT TIME ZONE 'UTC'`. |
| `cannot use generated column "x" in column generation expression` | The expression refers to another generated column | Repeat the underlying formula, or refer only to base columns. |
| `cannot use subquery in column generation expression` | The expression contains a `SELECT` | Move the logic to a trigger or a view. |
| A `DEFAULT` clause is rejected on the column | Generated columns cannot have defaults | Remove the `DEFAULT`. |
The exact wording of an error message can vary between PostgreSQL versions, so match on the idea rather than the full string.
Design guidelines
- Name the generated column for what it means, and keep the formula simple. A long expression is paid for on every write to its inputs.
- Put
NOT NULLon the base columns when a null input would give a meaningless result. Withfirst_name || ' ' || last_name, a null in either column makesfull_namenull, because||returns null when an operand is null. Useconcat_ws(' ', first_name, last_name)if you want nulls skipped.concat_wsis stable rather than immutable in PostgreSQL, so it fails the immutability check in a generation expression. In that case, constrain the base columns instead, or usecoalescearound each operand. - Test an expression with a plain
SELECTover sample rows before you commit it to a table definition. A wrong generated column costs a table rewrite to change, as a later chapter explains.
Exercise
You run the statement below and PostgreSQL reports "generation expression is not immutable". Why does it fail, and how do you change it so it works? CREATE TABLE logins (userid integer, at timestamptz NOT NULL, daylabel text GENERATED ALWAYS AS (to_char(at, 'YYYY-MM-DD')) STORED);
Show answer
tochar on a timestamptz is not immutable. Its result depends on the session time zone, so the same stored instant could produce different day labels in different sessions. To fix it, convert to a fixed time zone first, for example tochar(at AT TIME ZONE 'UTC', 'YYYY-MM-DD'). The day_label then means the UTC date.
Exercise
A table has columns price numeric(10,2) and taxrate numeric(4,3). Write a stored generated column named pricewithtax of type numeric(12,2) that equals price * (1 + taxrate), and say whether the table can also define a second generated column named pricerounded as round(pricewith_tax).
Show answer
pricewithtax numeric(12,2) GENERATED ALWAYS AS (price (1 + taxrate)) STORED. A second generated column cannot be defined as round(pricewith_tax), because a generation expression may not refer to another generated column. Write it from the base columns instead: round(price (1 + tax_rate)).