Sub topic 1
The problem: keeping derived values correct
Prerequisites
You should know basic SQL (CREATE TABLE, INSERT, UPDATE, SELECT), common PostgreSQL types such as text and integer, and what an index does. This chapter uses PostgreSQL 12 or later, the first version with stored generated columns.
Why derived values drift
Many tables hold a value computed from other columns in the same row, such as a full name built from a first and last name. If the application writes that value separately, the copies can drift apart. One code path may update lastname and forget fullname. A generated column avoids this by letting PostgreSQL compute the value itself.
Defining a generated column
A generated column is declared with GENERATED ALWAYS AS (expression). PostgreSQL evaluates the expression using other columns in the same row. The STORED keyword means the computed value is written to disk.
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
);Stored generated columns in practice
Insert rows without naming the generated column. PostgreSQL fills it in.
INSERT INTO people (first_name, last_name) VALUES ('Ada', 'Lovelace');
SELECT full_name FROM people; -- Ada LovelaceUpdating a source column recomputes the stored value:
UPDATE people SET last_name = 'King' WHERE first_name = 'Ada';
SELECT full_name FROM people; -- Ada KingWriting a value directly into the column is an error:
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"What the expression may contain
The expression may use columns from the same row, constants, operators, and immutable functions. An immutable function returns the same result for the same input every time. It cannot use other generated columns, other rows, or subqueries.
Expressions that depend on a session setting are rejected when the table is created. For example, to_char on a timestamptz value depends on the session time zone, so this statement 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
);Exercise
Why does the INSERT that supplies a value for full_name fail, and how would you change the statement so it succeeds?
Show answer
PostgreSQL accepts only DEFAULT for a generated column. Remove fullname from the column list, or write DEFAULT in its place, so PostgreSQL computes the value from firstname and last_name.