Store Derived Values Safely with PostgreSQL Generated Columns
Use PostgreSQL 12+ stored generated columns to compute derived values in the database and keep application logic from drifting out of sync.
04 Jun 2026, 02:41 UTC

The problem: derived logic living in two places
Many applications calculate a derived value—an invoice total, a normalized full name, or a status flag—in application code before writing a row. When two services or a database script and an API both perform that calculation, rounding rules or field mappings can drift. The database then stores rows whose derived columns disagree with the application’s expectations.
PostgreSQL 12 and later offers a built-in alternative: stored generated columns. The database computes the value from an expression you define and persists it on disk, so every client reads the same derived value without duplicating logic in application code.
How stored generated columns work
A stored generated column is declared with GENERATED ALWAYS AS (expression) STORED. PostgreSQL evaluates the expression during INSERT and UPDATE and writes the result to the table, just like a normal column. You can index it, filter on it, and reference it in constraints.
The expression must be immutable. It cannot reference other tables, sequences, set-returning functions, or volatile functions such as now() or random(). This restriction exists because PostgreSQL stores the result and cannot recompute it from outside state every time a row is read.
Worked example: invoice totals
Suppose an invoices table currently relies on application code to calculate total_cents from subtotal_cents and tax_rate. Move that calculation into the schema:
-- Run in psql connected to the target database.
-- The role needs CREATE privilege on the schema.
\c your_database
CREATE TABLE invoices (
id bigserial PRIMARY KEY,
customer_id text NOT NULL,
subtotal_cents integer NOT NULL CHECK (subtotal_cents >= 0),
tax_rate numeric(5,4) NOT NULL CHECK (tax_rate >= 0 AND tax_rate <= 1),
total_cents integer GENERATED ALWAYS AS (
subtotal_cents + round(subtotal_cents * tax_rate)
) STORED
);
Insert a row without mentioning the generated column:
INSERT INTO invoices (customer_id, subtotal_cents, tax_rate)
VALUES ('acme-001', 10000, 0.0825);
PostgreSQL stores the expression result for total_cents. If you attempt to insert a literal value into total_cents, PostgreSQL rejects it; omit the column or use DEFAULT instead.
When a base column changes, the generated value updates automatically:
UPDATE invoices
SET subtotal_cents = 15000
WHERE id = 1;
Because this is a state-changing schema operation, reversing it means dropping the column:
ALTER TABLE invoices DROP COLUMN total_cents;
Indexing and querying the derived value
Create an index on the generated column so queries that filter by the derived value can use an index scan:
CREATE INDEX idx_invoices_total_cents ON invoices (total_cents);
Verify the plan:
EXPLAIN SELECT * FROM invoices WHERE total_cents > 50000;
Look for Index Scan using idx_invoices_total_cents. On a small table the planner may still choose a sequential scan; run ANALYZE invoices; and re-check if you expect the index to be used at scale.
Confirming the column is stored-generated
Run this query against the database:
SELECT column_name, generation_expression
FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'invoices';
A generated column returns a non-null generation_expression. For additional confirmation, inspect the system catalog:
SELECT attname, attgenerated
FROM pg_attribute
WHERE attrelid = 'invoices'::regclass;
A stored generated column shows s in attgenerated; a regular column is empty.
Trade-offs and limits
- Write amplification: Every insert or update to the base columns recomputes and stores the generated value. High-write tables incur extra disk I/O and potential bloat.
- Immutable expressions only: You cannot generate values that depend on the current time, random numbers, or other tables. Avoid this feature for values such as “age as of today” that go stale without a row update.
- Expensive expression changes: Modifying the generation expression on a large table can rewrite the table and take an exclusive lock. Schedule the change during a maintenance window, or add a new column and backfill gradually instead.
- Not a validation replacement: Generated columns compute values; they do not replace transactions, check constraints, or application error handling.
Practical check before adopting
- Pick a derived value calculated only from columns in the same table and read more often than it changes.
- Add the generated column on a staging copy of the table.
- Run
EXPLAINon representative queries to confirm indexes on the generated column are used. - Measure write latency under load. If the recomputation cost is acceptable, promote the change to production.
Bottom line
PostgreSQL stored generated columns centralize derived-value logic in the database. They fit totals, normalized names, status flags, and similar row-local expressions. Use them when read frequency justifies the extra write cost, and skip them for anything that depends on real-time state outside the row.