Update And DROP EXPRESSION On Generated Columns
Recompute stored GENERATED ALWAYS AS columns with DEFAULT on UPDATE, then run DROP EXPRESSION to turn the column editable without losing stored rows.
Code
CREATE TEMP TABLE invoice_items (
item_id integer PRIMARY KEY,
unit_cents integer NOT NULL,
qty integer NOT NULL CHECK (qty > 0),
subtotal_cents integer GENERATED ALWAYS AS (unit_cents * qty) STORED
);
INSERT INTO invoice_items (item_id, unit_cents, qty) VALUES
(1, 1500, 2),
(2, 800, 3);
-- Changing base columns recomputes subtotal_cents; only DEFAULT is allowed explicitly
UPDATE invoice_items
SET qty = 4, subtotal_cents = DEFAULT
WHERE item_id = 1
RETURNING item_id, qty, subtotal_cents;
-- Convert the generated column into a regular writable column, preserving values
ALTER TABLE invoice_items
ALTER COLUMN subtotal_cents DROP EXPRESSION;
UPDATE invoice_items
SET subtotal_cents = 5500
WHERE item_id = 1
RETURNING item_id, unit_cents, qty, subtotal_cents;Code mechanics — Update And DROP EXPRESSION On Generated Columns
INSERT / UPDATE / CREATE / ALTER statements share the script, touching invoice_items.
invoice_items declares temporary per-session tables right here inside the script so pre-created database tables are unnecessary and everything drops on disconnect.
Breaking the statements into their working parts: a WHERE clause limiting a statement to the rows that qualify; a RETURNING clause that hands the affected rows back to the caller; a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Using it
The file brings its own tables (invoice_items) — session-local, created on the fly — so execute it whole against a database you can throw away.
Key statements
UPDATE invoice_items
SET qty = 4, subtotal_cents = DEFAULT
WHERE item_id = 1
RETURNING item_id, qty, subtotal_cents;
UPDATE invoice_items
SET subtotal_cents = 5500
WHERE item_id = 1
RETURNING item_id, unit_cents, qty, subtotal_cents;
CREATE TEMP TABLE invoice_items (
item_id integer PRIMARY KEY,
unit_cents integer NOT NULL,
qty integer NOT NULL CHECK (qty > 0),
subtotal_cents integer GENERATED ALWAYS AS (unit_cents * qty) STORED
);
Interactive Tools for This Topic
FAQ
- Name the tables involved in this file.
- `invoice_items` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.