Ira SQL ProIra SQL Pro

Generated Columns

intermediatepostgresql
2 min read

What are Generated Columns?

A generated column is a column whose value is automatically computed from an expression involving other columns in the same row. PostgreSQL supports stored generated columns, which are computed on write and stored on disk.

Syntax

CREATE TABLE products (
  id SERIAL PRIMARY KEY,
  price NUMERIC(10,2),
  tax_rate NUMERIC(4,2) DEFAULT 0.10,
  total_price NUMERIC(10,2) GENERATED ALWAYS AS (price * (1 + tax_rate)) STORED
);

When to Use

  • Automatically computing derived values (total = price * quantity)
  • Full names from first + last name
  • Ensuring derived columns are always consistent with source columns

Key Points

  1. STORED — PostgreSQL only supports STORED generated columns (computed on write, saved to disk).
  2. Cannot Insert/Update — You cannot set a generated column directly. It is always computed.
  3. Immutable Functions — The generation expression must use immutable functions only.
  4. No Subqueries — The expression cannot reference other tables or use subqueries.
  5. Indexable — You can create indexes on generated columns.

Guided Practice

Solve the challenge below. Use hints when stuck and check your answer for instant feedback.

Practice challengeGuided learning mode

Generated Columns Challenge

Write a query that solve this task: automatically combine first and last name.

Expected result

An employees table where full_name is automatically computed.

Hidden checks

  • Returned rows and values
  • Output columns and result shape
  • Final database state after the query runs

Lesson guidance

What are Generated Columns?

Initializing database...Each run starts from fresh sample data.

More Examples

Computed total price

Auto-compute total from price and quantity.

Initializing database...Each run starts from fresh sample data.

Frequently Asked Questions

Can I update a generated column?
No. Generated columns are read-only. Their value is automatically recomputed when source columns change.
Does PostgreSQL support virtual (non-stored) generated columns?
Not yet as of PostgreSQL 16. Only STORED generated columns are supported, meaning the value is physically saved on disk.

Related Topics