Sub topic 1
The problem: keeping derived values correct
A derived value is a value you can compute from other data you already store. Examples are an order line's total (quantity times unit price), a person's full name (first name plus last name), and a lowercase copy of an email address. This chapter explains why derived values go wrong in real systems and what you need from a solution. It sets up the rest of the tutorial, which covers PostgreSQL's built-in answer: generated columns.
Prerequisites
This chapter assumes you can already do the following:
- Write basic SQL:
CREATE TABLE,INSERT,UPDATE, andSELECT. - Use common PostgreSQL types such as
text,integer,numeric, andtimestamptz. - Explain what an index is and why it speeds up lookups.
- Tell a table from a view. A view is a stored query that behaves like a table when you read from it.
You do not need to know anything about triggers or PL/pgSQL beyond reading the short example below.
Why derived values exist at all
Normalization says you should store each fact once. A derived value is a second copy of a fact, so you would not normally store it. People store derived values anyway, for three reasons.
- Convenience. Every query that needs the full name would otherwise repeat
first_name || ' ' || last_name. One shared definition is easier to read and harder to get wrong. - Speed. A stored value can be indexed. Searching
WHERE lower(email) = '[email protected]'on a large table is slow without an index on that exact expression. - Contracts with other systems. An export job, a reporting tool, or a BI dashboard may expect a plain column. It cannot call your expression.
Each reason has a cost. The moment you store a derived value, you have two places that must agree, and the database does not know they are related. Keeping them in agreement becomes your job.
A worked example of drift
Here is an order-lines table where the application maintains line_total itself.
CREATE TABLE order_lines (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
quantity integer NOT NULL CHECK (quantity > 0),
unit_price numeric(10,2) NOT NULL,
line_total numeric(12,2) NOT NULL
);
INSERT INTO order_lines (quantity, unit_price, line_total)
VALUES (3, 9.99, 29.97);The row is correct: 3 × 9.99 = 29.97. Now a support script changes the quantity and does not know that line_total exists.
UPDATE order_lines SET quantity = 5 WHERE id = 1;
SELECT quantity,
unit_price,
line_total,
quantity * unit_price AS expected_total
FROM order_lines;The result is:
| quantity | unit_price | line_total | expected_total |
|---|---|---|---|
| 5 | 9.99 | 29.97 | 49.95 |
Nothing failed. PostgreSQL has no way to know that line_total should follow quantity, so it accepted both statements. The table now contains a lie, and every report that reads line_total will be wrong by 19.98 for this row.
You can find rows like this with an audit query:
SELECT id
FROM order_lines
WHERE line_total <> quantity * unit_price;Running an audit like this regularly is a sign of the problem. You are checking an invariant that the database could have enforced.
Where drift comes from
Drift is rarely one big mistake. It comes from many small paths that each skip the recalculation. The diagram shows the usual ones.
The common causes are:
- Multiple writers. Your web app, a batch job, a data-migration script, and an analyst with write access all touch the table. Each one has to implement the formula, and each copy can differ.
- Formula changes. If the definition changes, say a rounding rule, old rows keep the old result unless someone backfills them.
- Partial updates. A statement that changes only
quantityis correct as SQL. It is wrong for the application unless it also setsline_total. - Bulk paths.
COPY,INSERT ... SELECT, and ORM bulk operations often bypass the application-layer code that normally computes the value. - Rounding differences. The application computes in floating point and rounds one way, while SQL uses
numericand rounds another. The two values drift apart by a cent.
The usual fixes and their weaknesses
Teams have solved this problem in several ways. Each way has a gap.
Compute it in application code
You write the formula once in a helper and call it everywhere. This works only if every writer uses the helper. Scripts, other services, and manual SQL do not. Nothing in the database enforces the rule.
Recompute it on every read
You do not store the value. Each query calculates quantity * unit_price itself. This cannot drift, but the formula is copied into every query, and you cannot index it unless you build an expression index. It also does not help consumers that need a real column.
Hide the formula in a view
CREATE VIEW order_lines_v AS
SELECT id,
quantity,
unit_price,
quantity * unit_price AS line_total
FROM order_lines_base;This assumes a base table named order_lines_base that has no line_total column. The view gives readers one shared definition and cannot drift. Readers must query the view instead of the table, and you cannot index the computed column. Writers also cannot use the view for ordinary inserts into line_total, which is usually what you want, but the table and its view are now two objects to keep in step.
Maintain it with a trigger
A trigger is a function that PostgreSQL runs automatically when a row is inserted, updated, or deleted. This function recalculates the total:
CREATE FUNCTION set_line_total() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.line_total := NEW.quantity * NEW.unit_price;
RETURN NEW;
END;
$$;
CREATE TRIGGER order_lines_set_total
BEFORE INSERT OR UPDATE ON order_lines
FOR EACH ROW EXECUTE FUNCTION set_line_total();A BEFORE trigger runs before the row is written and before the NOT NULL check. That means writers can leave line_total out of an INSERT and still satisfy the constraint. Triggers close most of the gap, and they are the traditional answer. They have costs of their own:
- They can be switched off.
ALTER TABLE ... DISABLE TRIGGERturns one off, andsession_replication_role = replicaskips ordinary triggers. Both are used during maintenance and data loads, and both reopen the gap. - They can be overwritten by another trigger. Triggers on the same event run in alphabetical order by name. A later trigger can change the value again.
- They are code to maintain. You need a function and a trigger for each table, plus tests. Copying the pattern to ten tables gives you ten functions to keep correct.
- They hide behavior. A developer reading
CREATE TABLEsees a plainnumericcolumn. Nothing there says the column is computed. - Writers can still try to set it. Without extra checks,
INSERT ... (line_total) VALUES (1)is silently overwritten by the trigger. The caller never learns that their value was discarded.
Use a constraint to detect it
You could add a CHECK (line_total = quantity * unit_price) constraint. That turns silent drift into an error, which is an improvement. The writer must still compute the right value, so the burden stays on the writer. You have moved the failure from "wrong data" to "rejected statement", but nobody has removed the work.
What you actually want
The examples above point to a short list of properties for a good solution.
| Property | Why it matters |
|---|---|
| Defined once, in the table | One formula, visible in the schema, not scattered across code. |
| Applied by the database on every write path | `COPY`, scripts, and manual SQL all get the same result. |
| Cannot be overwritten by mistake | A writer who supplies a conflicting value gets an error, not a silent change. |
| Usable like an ordinary column | It can be selected, filtered, and, when stored, indexed. |
| Cheap to reason about | A reader of the table definition can see what the value means. |
PostgreSQL's generated columns are designed to meet these properties. The following example previews the idea. The details come in later chapters.
CREATE TABLE order_lines_gen (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
quantity integer NOT NULL CHECK (quantity > 0),
unit_price numeric(10,2) NOT NULL,
line_total numeric(12,2) GENERATED ALWAYS AS (quantity * unit_price) STORED
);
INSERT INTO order_lines_gen (quantity, unit_price) VALUES (3, 9.99);
UPDATE order_lines_gen SET quantity = 5 WHERE id = 1;
SELECT line_total FROM order_lines_gen; -- 49.95The formula lives in the table definition. The database recomputes line_total on the UPDATE, and no writer can set it to a different value. The scripted fix, the bulk import, and the manual psql session all produce the same result.
What generated columns do not solve
A generated column computes its value from other columns in the same row. That scope is narrow on purpose, and it rules out several kinds of derived data.
- Values from other rows or tables. An order's total, which sums all of its lines, cannot be a generated column. The expression cannot run a subquery or read another row.
- Values that depend on time or session state. The age of a person changes every day, and the result of a function can depend on the session time zone. A generated column must always produce the same result for the same inputs, which is the immutability rule covered later.
- Values that need side effects. Writing to an audit table or calling an external service does not fit an expression.
- Values that should be editable. If users sometimes need to override the computed result, a generated column rejects the override.
For those cases you will still use views, triggers, materialized views, or application logic. The final chapter in this tutorial helps you choose among them.
A decision checklist before you add a derived value
Before storing a second copy of anything, ask these questions in order.
- Do you need it stored? If the expression is cheap and you only need it in a few queries, a view or a repeated expression may be enough.
- Do you need to index it? If yes, you need either a stored column or an expression index.
- Does it depend only on the same row? If it needs other rows, a generated column cannot do it.
- Is every input deterministic? The output must depend only on column values and on functions that always return the same answer for the same arguments.
- Who writes to the table? The more independent writers there are, the more a database-enforced rule is worth.
- Can the value ever be overridden legitimately? If yes, keep it as an ordinary column with a
CHECKconstraint or a trigger.
If the answers are "same row", "deterministic", and "many writers", you have the case that generated columns fit best.
Summary
Storing a derived value creates two copies of a fact, and PostgreSQL does not know they are related unless you tell it. Drift happens through any write path that forgets the formula: scripts, bulk loads, manual fixes, and partial updates. Application helpers, views, CHECK constraints, and triggers each close part of the gap but leave another open. A good solution defines the formula once in the table, applies it on every write, rejects conflicting writes, and behaves like an ordinary column. Generated columns aim at exactly that for values that depend only on other columns of the same row.
Exercise
In the order_lines table from this chapter, a bulk UPDATE order_lines SET unit_price = unit_price * 1.10 is run. What is wrong with the data afterwards, and which query finds the affected rows?
Show answer
line_total is no longer equal to quantity * unit_price for every row, because the stored total was not recalculated when the price changed. The query SELECT id FROM order_lines WHERE line_total <> quantity * unit_price; lists the rows that disagree. (Rounding may leave a few rows that still match.)
Exercise
A trigger keeps line_total correct, yet a nightly data-load job still produces rows with wrong totals. Name two ways the trigger could have been bypassed.
Show answer
The job may have disabled the trigger with ALTER TABLE ... DISABLE TRIGGER, or it may run with session_replication_role = replica, which skips ordinary triggers. Another trigger firing later on the same event could also have overwritten the value.
Exercise
You want an order's order_total, the sum of all its line totals, to be maintained automatically. Can this be a generated column on the orders table? Explain briefly.
Show answer
No. A generated column may use only other columns of the same row. Summing lines needs data from other rows in another table, so you need a trigger, a view, a materialized view, or application logic instead.