When Derived Data Needs Consistency: Using PostgreSQL Stored Generated Columns
Use PostgreSQL's <code>GENERATED ALWAYS AS (...) STORED</code> columns when data consistency across reads is paramount. This feature persists derived values, eliminating redundant computation during queries, though it increases write costs.
06 Jun 2026, 14:27 UTC

Avoiding Inconsistent Derived Data in PostgreSQL
The problem isn't just calculating a derived value (like a full name from first and last); it's ensuring that every read always reflects the exact, current calculation without the application having to re-run the logic every single time. The useful takeaway is this: use PostgreSQL's GENERATED ALWAYS AS (...) STORED columns when data consistency across reads is paramount, accepting a small cost on writes.
Stored vs. Virtual Generation
PostgreSQL supports generated columns since version 12. There are two types: STORED and VIRTUAL. A STORED column computes its value at insert or update time and physically saves it on disk. A VIRTUAL column computes the value only when queried. For consistency, STORED is necessary because it eliminates redundant computation during reads.
Design Constraints and Use Cases
These columns are excellent for normalized, row-level derivations, such as combining first_name and last_name into full_name, or calculating a row-level total from line item components. Crucially, they cannot reference other generated columns in a way that creates a circular dependency, nor can they use volatile functions or subqueries.
Example: Calculating Full Name
Consider a users table. We want full_name to always match first_name and last_name.
ALTER TABLE users ADD COLUMN full_name VARCHAR GENERATED ALWAYS AS (first_name || ' ' || last_name) STORED;Where to run: psql connected to the target database. Permissions: Superuser or appropriate schema modification rights. Check: Run \d users and confirm full_name lists the generation expression.
Trade-Off: Write Amplification
The primary limitation is write cost. Every INSERT or UPDATE to first_name or last_name triggers the computation and persistence of full_name. On very high-volume tables, this write amplification and associated locking time must be monitored. Do not use this to replace materialized views if the derivation requires aggregation across many rows.
To verify the behavior, insert a user, then update only last_name, and confirm full_name updates automatically without the UPDATE statement referencing full_name.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.