Sub topic 5
How INSERT and UPDATE treat generated columns
This chapter assumes you can write basic INSERT, UPDATE and SELECT statements. It also assumes you have seen the GENERATED ALWAYS AS (...) STORED syntax from the earlier chapters. Here you will learn what PostgreSQL does with a generated column when you write rows: when it computes the value, what it refuses to accept, and which errors you can expect.
The examples use stored generated columns. Where PostgreSQL 18 virtual columns behave differently, the text says so.
The core rule: you never supply the value
A generated column is owned by PostgreSQL. Your statements may read it, but they cannot give it a value. The only thing you can write to it is the keyword DEFAULT, which means "compute it as usual".
This table is used throughout the chapter:
CREATE TABLE order_lines (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
unit_price numeric(10,2) NOT NULL,
quantity integer NOT NULL,
discount numeric(4,2) NOT NULL DEFAULT 0,
line_total numeric(12,2) GENERATED ALWAYS AS
(round(unit_price * quantity * (1 - discount), 2)) STORED
);discount is a fraction, so 0.10 means 10 percent. The round(numeric, integer) function is immutable, so the expression is allowed.
INSERT
Leave the generated column out of the column list. PostgreSQL evaluates the expression against the new row and stores the result.
INSERT INTO order_lines (unit_price, quantity)
VALUES (9.50, 3)
RETURNING id, line_total;The RETURNING clause reports line_total as 28.50. For a stored column, RETURNING shows the value that was written to disk.
You can also name the column and give it DEFAULT. This is useful when you build an INSERT with a fixed list of columns, or when you write INSERT INTO t VALUES (...) without a column list and need a placeholder for every position:
INSERT INTO order_lines (unit_price, quantity, line_total)
VALUES (4.00, 10, DEFAULT);Any other value is an error:
INSERT INTO order_lines (unit_price, quantity, line_total)
VALUES (4.00, 10, 99.00);
-- ERROR: cannot insert a non-DEFAULT value into column "line_total"
-- DETAIL: Column "line_total" is a generated column.The same rule applies to INSERT ... SELECT. The select list cannot feed a computed value into the generated column. Omit the column and let PostgreSQL compute it.
UPDATE
When an UPDATE changes a column that the expression uses, PostgreSQL recomputes the generated column as part of the same row update. You do not mention the generated column at all.
UPDATE order_lines SET quantity = 4 WHERE id = 1 RETURNING line_total;
-- 38.00
UPDATE order_lines SET discount = 0.10 WHERE id = 1 RETURNING line_total;
-- 34.20The recomputation is part of the row version being written. After the statement commits, no other session can see a row where quantity is new and line_total is old.
Direct assignment is rejected, with a different message from the INSERT case:
UPDATE order_lines SET line_total = 5 WHERE id = 1;
-- ERROR: column "line_total" can only be updated to DEFAULT
-- DETAIL: Column "line_total" is a generated column.SET line_total = DEFAULT is legal. It forces a recomputation, but the result equals the current value unless something unusual happened, so you rarely need it.
An UPDATE that touches unrelated columns
If an UPDATE changes only columns that the generation expression does not reference, PostgreSQL has no reason to change the generated value. The old stored value stays. This is correct because the expression is immutable: the same inputs always give the same output.
The same fact has a cost. If you index a stored generated column, an update to one of its inputs changes an indexed value. That update cannot be a heap-only tuple (HOT) update, so it is slower than an update of an unindexed column.
The order of events inside one row write
Several things happen to a row on its way to disk, and the order explains most surprises.
Three consequences follow from this order.
- A
BEFOREtrigger can change base columns, and the generated column reflects the change. ABEFOREtrigger cannot read the generated column's new value, because it does not exist yet. - A
CHECKorNOT NULLconstraint on a generated column tests the computed value. This is how you reject rows whose derived result is invalid. - An
AFTERtrigger sees the final stored value.
Here is a BEFORE trigger that caps the quantity:
CREATE FUNCTION cap_quantity() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.quantity > 100 THEN
NEW.quantity := 100;
END IF;
RETURN NEW;
END
$$;
CREATE TRIGGER order_lines_cap
BEFORE INSERT OR UPDATE ON order_lines
FOR EACH ROW EXECUTE FUNCTION cap_quantity();
INSERT INTO order_lines (unit_price, quantity)
VALUES (9.50, 500)
RETURNING quantity, line_total;
-- quantity = 100, line_total = 950.00The total is computed from the capped quantity, not from the 500 the client sent.
Constraints see the computed value
Because constraints run after the computation, you can guard derived results:
ALTER TABLE order_lines
ADD CONSTRAINT line_total_not_negative CHECK (line_total >= 0);
UPDATE order_lines SET discount = 1.50 WHERE id = 1;
-- ERROR: new row for relation "order_lines" violates check constraint
-- "line_total_not_negative"A discount of 1.50 makes (1 - discount) negative. The failing statement is rolled back like any other constraint failure, and the row keeps its previous values.
Errors raised by the expression itself
The generation expression runs inside your INSERT or UPDATE. If it raises an error, your statement fails. This applies to division by zero, numeric overflow and invalid casts.
CREATE TABLE ratios (
numerator integer NOT NULL,
denominator integer NOT NULL,
ratio integer GENERATED ALWAYS AS (numerator / denominator) STORED
);
INSERT INTO ratios (numerator, denominator) VALUES (10, 2); -- ratio = 5
INSERT INTO ratios (numerator, denominator) VALUES (1, 0);
-- ERROR: division by zero
UPDATE ratios SET denominator = 0;
-- ERROR: division by zeroThe failure lands on the statement that wrote the bad input, even though the column you changed is not the one that failed. Write defensive expressions when inputs can be unusual, for example numerator / NULLIF(denominator, 0). That expression produces NULL instead of an error.
A stored column fails at write time. A PostgreSQL 18 virtual column fails at read time instead, because it is computed in SELECT. A bad row can then be stored successfully and break later queries. This is one reason the stored/virtual comparison in a later chapter matters.
NULL handling
NULL propagates through most operators. With the people table from the earlier chapter, first_name || ' ' || last_name returns NULL if either part is NULL. The NOT NULL constraints on those columns prevent that. If a base column can be NULL, choose a function that handles it:
CREATE TABLE contacts (
first_name text,
last_name text,
display text GENERATED ALWAYS AS
(concat_ws(' ', first_name, last_name)) STORED
);concat_ws skips NULL arguments, so a contact with only a last name gets display = 'Lovelace'. concat_ws is immutable when its arguments are text, so it is allowed here.
ON CONFLICT and upserts
The rules for INSERT ... ON CONFLICT DO UPDATE are the same. The SET list cannot assign to a generated column unless the value is DEFAULT. When the conflict path updates a row, PostgreSQL recomputes the generated column from the resulting row values. The EXCLUDED pseudo-row also exposes the generated column's value as computed for the proposed row, so you can reference it in the SET clause of other columns.
COPY
COPY ... FROM follows the same ownership rule. Without a column list, PostgreSQL skips generated columns and computes them for each loaded row. Naming a generated column in the COPY FROM column list is an error. So a file exported with all columns, including a generated one, cannot be loaded back without an explicit column list that leaves the generated column out.
Which generated columns COPY TO exports without a column list has changed across versions. If you rely on it, test on your version, or list the columns explicitly.
Summary of behavior
| Statement | Generated column omitted | Set to `DEFAULT` | Set to another value |
|---|---|---|---|
| `INSERT` | Computed | Computed | Error: cannot insert a non-DEFAULT value |
| `UPDATE` | Recomputed if an input changed | Recomputed | Error: can only be updated to DEFAULT |
| `COPY FROM` | Computed | Not applicable | Error if the column is listed |
Common mistakes
- Writing the application layer as if the column were editable. ORMs often include every column in
INSERTandUPDATE. Mark the field as read-only or database-computed, or you will see the errors above. - Expecting a trigger to see the computed value. A
BEFOREtrigger runs first. Use anAFTERtrigger or repeat the expression. - Blaming the wrong column. An error such as
division by zeropoints at the statement, not at the generated column. Check the generation expressions on the table. - Ignoring index cost. Indexed generated columns turn updates of their inputs into non-HOT updates.
Exercise
A table has columns a integer NOT NULL, b integer NOT NULL and c integer GENERATED ALWAYS AS (a / b) STORED. A client runs UPDATE t SET a = 7 WHERE id = 3, and the row with id 3 has b = 0. What happens, and why does the error appear even though the client never touched b or c?
Show answer
The statement fails with "division by zero" and the row keeps its old values. The update changes a, which c's expression uses, so PostgreSQL recomputes c as part of the update. The expression evaluates 7 / 0 inside the statement, and the error aborts it. Fix the expression with NULLIF(b, 0), or ensure b can never be 0 with a CHECK constraint.
Exercise
Using the orderlines table and its BEFORE trigger capquantity, what are the values of quantity and linetotal after INSERT INTO orderlines (unit_price, quantity) VALUES (2.00, 250)? Which step in the write order makes this the result?
Show answer
quantity is 100 and linetotal is 200.00. BEFORE ROW triggers run first and change quantity from 250 to 100. PostgreSQL then computes the stored generated column from the modified row, so linetotal is 2.00 100 (1 - 0) = 200.00.