Generated Columns and Domains

Updated · 9 min read
mediumPostgreSQL 18sqlgenerated-columnscomputed-columnsdomainsenuminterview

A generated column in SQL is a column whose value the database calculates from other columns in the same row, such as how many days late a payment was, from its due date and paid date. You never insert or update it yourself; it always stays correct. Two related features let the database enforce rules for you: a domain is a data type with a built-in rule, such as "a dollar amount greater than zero", and an enumerated type is a type with a fixed list of allowed values. In this lesson, we will add a generated column to payments, compare stored and virtual columns, create a domain and an enum, and see the limits of each.

In One Minute

  • col type GENERATED ALWAYS AS (expression) calculates a column from the same row.
  • STORED saves the value on every write; VIRTUAL calculates it on every read (PostgreSQL 18's default).
  • Generated values can't be written directly, and the expression may use only immutable functions and the same row.
  • CREATE DOMAIN usd_amount AS NUMERIC(8,2) CHECK (VALUE > 0) makes a reusable type with a rule.
  • CREATE TYPE pay_method AS ENUM ('card', 'check', 'cash') allows only those values, sorted in that order.

Syntax

SQL
column_name data_type GENERATED ALWAYS AS (expression) [STORED | VIRTUAL]
 
CREATE DOMAIN domain_name AS data_type [NOT NULL] [CHECK (condition using VALUE)];
 
CREATE TYPE type_name AS ENUM ('value1', 'value2', ...);

A Generated Column

Days late is a fact that can be computed from two other columns, so instead of storing and maintaining it by hand, let the database compute it:

SQL▶ Try it
ALTER TABLE payments
  ADD COLUMN days_late INTEGER
  GENERATED ALWAYS AS (GREATEST(paid_on - due_on, 0)) STORED;
 
SELECT payment_id, due_on, paid_on, days_late
FROM payments
ORDER BY payment_id;
Output
ALTER TABLE
 
 payment_id |   due_on   |  paid_on   | days_late
------------+------------+------------+-----------
          1 | 2025-09-01 | 2025-08-28 |         0
          2 | 2025-11-01 | 2025-10-30 |         0
          3 | 2025-12-01 | 2025-12-03 |         2
          4 | 2026-01-02 | 2025-12-29 |         0
          5 | 2026-01-05 | 2026-01-05 |         0
          6 | 2025-11-15 | 2025-11-14 |         0
          7 | 2025-12-15 | 2025-12-19 |         4
(7 rows)

Explanation: Adding the column computed days_late for every existing row: payment 3 was 2 days late and payment 7 was 4. Subtracting dates gives days, and GREATEST(..., 0) turns early payments into 0. If someone later corrects a paid_on date, days_late updates with it.

days_late = GREATEST(paid_on - due_on, 0), computed by the database for every payment

A generated column can't be written to directly, which is exactly what keeps it correct:

SQL▶ Try it
ALTER TABLE payments
  ADD COLUMN days_late INTEGER
  GENERATED ALWAYS AS (GREATEST(paid_on - due_on, 0)) STORED;
 
UPDATE payments SET days_late = 0 WHERE payment_id = 7;
 
UPDATE payments SET paid_on = '2025-12-15' WHERE payment_id = 7;
 
SELECT payment_id, due_on, paid_on, days_late FROM payments WHERE payment_id = 7;
Output
ALTER TABLE
 
ERROR:  column "days_late" can only be updated to DEFAULT
DETAIL:  Column "days_late" is a generated column.
 
UPDATE 1
 
 payment_id |   due_on   |  paid_on   | days_late
------------+------------+------------+-----------
          7 | 2025-12-15 | 2025-12-15 |         0
(1 row)

Explanation: Setting days_late directly is refused. Correcting the real fact, paid_on, recalculates it: payment 7 is now on time.

Stored vs Virtual

STOREDVIRTUAL (PostgreSQL 18 default)
CalculatedOn every insert and updateOn every read
Takes disk spaceYesNo
Can be indexedYesNo (in PostgreSQL 18)
Good forExpensive expressions, indexed or searched valuesCheap expressions

Leaving out the keyword gives a virtual column in PostgreSQL 18 (earlier versions supported only STORED). The catalog shows which is which:

SQL▶ Try it
ALTER TABLE payments ADD COLUMN days_late INTEGER GENERATED ALWAYS AS (GREATEST(paid_on - due_on, 0)) STORED;
ALTER TABLE payments ADD COLUMN amount_cents INTEGER GENERATED ALWAYS AS ((amount_usd * 100)::INTEGER);
 
SELECT attname AS column_name, attgenerated AS kind
FROM pg_attribute
WHERE attrelid = 'payments'::regclass AND attgenerated <> ''
ORDER BY attname;
 
CREATE INDEX payments_cents_idx ON payments (amount_cents);
Output
ALTER TABLE
 
ALTER TABLE
 
 column_name  | kind
--------------+------
 amount_cents | v
 days_late    | s
(2 rows)
 
ERROR:  indexes on virtual generated columns are not supported

Explanation: s means stored and v means virtual. amount_cents was declared without a keyword, so it's virtual, and PostgreSQL 18 refuses to index it. The full-text search column in Full-Text Search was declared STORED so it could have a GIN index.

STORED saves the value when the row is written; VIRTUAL computes it each time the row is read

Limits

The expression may use only columns of the same row and immutable functions, so its value can never change unless the row does:

SQL▶ Try it
ALTER TABLE payments
  ADD COLUMN days_since_paid INTEGER
  GENERATED ALWAYS AS (CURRENT_DATE - paid_on) STORED;
Output
ERROR:  generation expression is not immutable

Explanation: CURRENT_DATE changes every day, so a stored "days since paid" would go stale. Compute values like that in the query instead: SELECT CURRENT_DATE - paid_on.

Domains: Types with Rules

A domain is a named data type with constraints attached, defined once and used in many tables:

SQL▶ Try it
CREATE DOMAIN usd_amount AS NUMERIC(8,2)
  CHECK (VALUE > 0);
 
CREATE TABLE refunds (
  refund_id  INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  payment_id INTEGER NOT NULL REFERENCES payments (payment_id),
  amount_usd usd_amount NOT NULL
);
 
INSERT INTO refunds (payment_id, amount_usd) VALUES (3, 50.00);
INSERT INTO refunds (payment_id, amount_usd) VALUES (7, -10.00);
 
SELECT refund_id, payment_id, amount_usd FROM refunds;
Output
CREATE DOMAIN
 
CREATE TABLE
 
INSERT 0 1
 
ERROR:  value for domain usd_amount violates check constraint "usd_amount_check"
 
 refund_id | payment_id | amount_usd
-----------+------------+------------
         1 |          3 |      50.00
(1 row)

Explanation: Inside a domain's CHECK, VALUE means the value being stored. The table only says amount_usd usd_amount, but the rule comes with it: the negative refund is rejected. Any other table that uses usd_amount gets the same rule, and changing the domain changes it everywhere.

Enumerated Types

An enum is a type whose values come from a fixed list, and which sorts in the list's order, not alphabetically:

SQL▶ Try it
CREATE TYPE enrollment_stage AS ENUM ('applied', 'active', 'completed');
 
CREATE TABLE stage_history (
  student_id INTEGER NOT NULL,
  stage      enrollment_stage NOT NULL
);
 
INSERT INTO stage_history VALUES
  (103, 'completed'), (103, 'applied'), (103, 'active');
 
SELECT stage FROM stage_history ORDER BY stage;
 
INSERT INTO stage_history VALUES (103, 'paused');
Output
CREATE TYPE
 
CREATE TABLE
 
INSERT 0 3
 
   stage
-----------
 applied
 active
 completed
(3 rows)
 
ERROR:  invalid input value for enum enrollment_stage: "paused"

Explanation: Sorting follows the declared order, applied, active, completed, which alphabetical order would get wrong. A value not on the list, 'paused', is rejected. Adding a value later takes ALTER TYPE enrollment_stage ADD VALUE 'paused'; removing or renaming values is much harder.

A domain carries its CHECK rule into every table; an enum allows only its list of values, in order

In Other Databases

FeaturePostgreSQLMySQLSQL Server
Generated columnGENERATED ALWAYS AS (...) STORED or VIRTUALSame syntax; VIRTUAL is the defaultComputed column: col AS (expr) [PERSISTED]
DomainCREATE DOMAIN ... CHECKNoneAlias types (CREATE TYPE ... FROM), without checks
EnumCREATE TYPE ... AS ENUMENUM('a', 'b') written in the columnNone; use CHECK

Tabs showing each database's version are coming to this course.

Common Mistakes

Storing values that can be derived. A hand-maintained days_late goes wrong the first time someone forgets it.

Trying to insert or update a generated column. Change its source columns instead.

Using time-dependent functions in a generated column. now() and CURRENT_DATE aren't allowed; compute them in queries.

Expecting to index a virtual column. In PostgreSQL 18, declare it STORED to index it.

Interview Corner

What is a generated (computed) column?

A column whose value the database computes from other columns in the same row, using a fixed expression. It can be stored on write or computed on read, and it can't be set directly.

What's the difference between STORED and VIRTUAL generated columns?

A stored column is computed when the row is written and takes disk space, and can be indexed. A virtual one is computed when read and takes no space.

What is a domain in SQL?

A user-defined data type based on an existing type, with optional NOT NULL and CHECK constraints, so a rule can be reused across many columns.

Practice

Challenge: Add a stored generated column fee_with_tax to courses that adds 8.25% tax to fee_usd, rounded to cents, then raise Git Basics' fee to 300.00 and show both columns for Git Basics.

Show solution
SQL▶ Try it
ALTER TABLE courses
  ADD COLUMN fee_with_tax NUMERIC(8,2)
  GENERATED ALWAYS AS (round(fee_usd * 1.0825, 2)) STORED;
 
UPDATE courses SET fee_usd = 300.00 WHERE title = 'Git Basics';
 
SELECT title, fee_usd, fee_with_tax
FROM courses
WHERE title = 'Git Basics';
Output
ALTER TABLE
 
UPDATE 1
 
   title    | fee_usd | fee_with_tax
------------+---------+--------------
 Git Basics |  300.00 |       324.75
(1 row)

Updating the fee recalculated the tax automatically. round and multiplication are immutable, so the expression is allowed.

Quick check: Generated columns and domains

3 questions
1What happens when you UPDATE a generated column directly?
2Which generated column can't use CURRENT_DATE?
3In what order does ORDER BY sort an enum column?

Key Takeaways

You want toWrite
A computed columncol INTEGER GENERATED ALWAYS AS (expr) STORED
A reusable ruleCREATE DOMAIN usd_amount AS NUMERIC(8,2) CHECK (VALUE > 0);
A fixed listCREATE TYPE stage AS ENUM ('applied', 'active', 'completed');
Add an enum valueALTER TYPE stage ADD VALUE 'paused';

Was this tutorial helpful?

Lesson 90 of 115