🐘 PostgreSQL Intermediate

What are generated columns in PostgreSQL?

Answer

Generated columns (PostgreSQL 12+) are columns whose values are automatically computed from other columns. STORED generated columns are physically stored and computed on insert/update: ALTER TABLE products ADD COLUMN price_with_tax NUMERIC GENERATED ALWAYS AS (price * 1.18) STORED;. They cannot be inserted into or updated manually (GENERATED ALWAYS). Useful for: pre-computing expensive expressions, creating FTS vectors, storing derived values for indexing. GENERATED ALWAYS AS IDENTITY is different — it's for auto-increment primary keys (successor to SERIAL). You can index a generated column normally. Generated columns cannot reference other generated columns, user-defined functions (non-immutable), or sequences.