Generated Columns and Domains
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.STOREDsaves the value on every write;VIRTUALcalculates 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
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:
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;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.
A generated column can't be written to directly, which is exactly what keeps it correct:
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;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
STORED | VIRTUAL (PostgreSQL 18 default) | |
|---|---|---|
| Calculated | On every insert and update | On every read |
| Takes disk space | Yes | No |
| Can be indexed | Yes | No (in PostgreSQL 18) |
| Good for | Expensive expressions, indexed or searched values | Cheap expressions |
Leaving out the keyword gives a virtual column in PostgreSQL 18 (earlier versions supported only STORED). The catalog shows which is which:
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);ALTER TABLE
ALTER TABLE
column_name | kind
--------------+------
amount_cents | v
days_late | s
(2 rows)
ERROR: indexes on virtual generated columns are not supportedExplanation: 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.
Limits
The expression may use only columns of the same row and immutable functions, so its value can never change unless the row does:
ALTER TABLE payments
ADD COLUMN days_since_paid INTEGER
GENERATED ALWAYS AS (CURRENT_DATE - paid_on) STORED;ERROR: generation expression is not immutableExplanation: 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:
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;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:
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');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.
In Other Databases
| Feature | PostgreSQL | MySQL | SQL Server |
|---|---|---|---|
| Generated column | GENERATED ALWAYS AS (...) STORED or VIRTUAL | Same syntax; VIRTUAL is the default | Computed column: col AS (expr) [PERSISTED] |
| Domain | CREATE DOMAIN ... CHECK | None | Alias types (CREATE TYPE ... FROM), without checks |
| Enum | CREATE TYPE ... AS ENUM | ENUM('a', 'b') written in the column | None; 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
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';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.
Key Takeaways
| You want to | Write |
|---|---|
| A computed column | col INTEGER GENERATED ALWAYS AS (expr) STORED |
| A reusable rule | CREATE DOMAIN usd_amount AS NUMERIC(8,2) CHECK (VALUE > 0); |
| A fixed list | CREATE TYPE stage AS ENUM ('applied', 'active', 'completed'); |
| Add an enum value | ALTER TYPE stage ADD VALUE 'paused'; |
Was this tutorial helpful?