Sub topic 2
How INSERT and UPDATE treat generated columns
This chapter assumes you know basic SQL (CREATE TABLE, INSERT, UPDATE, SELECT), common PostgreSQL types such as text and integer, and what an index does.
A generated column is a column whose value PostgreSQL computes from other columns in the same row. You cannot set it directly, so INSERT and UPDATE follow strict rules for it.
Writing to a stored generated column
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');
UPDATE people SET last_name = 'King' WHERE first_name = 'Ada';
SELECT full_name FROM people; -- 'Ada King'- INSERT may omit the column or write DEFAULT. Any other value fails.
- UPDATE may set the column to DEFAULT. Any other value fails.
- When a source column changes, PostgreSQL recomputes the value in the same statement.
INSERT INTO people (first_name, last_name, full_name)
VALUES ('Grace', 'Hopper', 'Someone Else');
-- ERROR: cannot insert a non-DEFAULT value into column "full_name"Virtual generated columns
PostgreSQL 18 and later accept VIRTUAL in place of STORED:
CREATE TABLE rectangles (
width integer NOT NULL,
height integer NOT NULL,
area integer GENERATED ALWAYS AS (width * height) VIRTUAL
);A virtual column saves no value on disk. PostgreSQL computes it when a query reads it. The write rules stay the same: you still cannot set it directly. Writes skip the computation and use no extra space, but every read pays for it.
Choosing between stored and virtual
| Factor | Stored | Virtual |
|---|---|---|
| Disk space | One saved value per row | None |
| Extra work on INSERT or UPDATE | Computes the expression | None |
| Work on SELECT | Reads the saved value | Computes the expression |
| Direct index | Yes | No |
| Version needed | All supported versions | PostgreSQL 18 and later |
Choose stored when reads are frequent or you need an index. Choose virtual when writes are frequent, the expression is cheap, and the server runs PostgreSQL 18 or later.
Exercise
Using the people table, what does UPDATE people SET firstname = 'Augusta' WHERE lastname = 'Lovelace' do to full_name?
Show answer
PostgreSQL recomputes full_name in the same statement, so it becomes 'Augusta Lovelace'. No application code or extra statement is needed.