Part 10 / Topic 8 of 9
Enums and domains
Two ways to teach the type system your vocabulary.
Enums — a type whose values are a fixed list. shopdb constrains orders.status with a CHECK; the enum spelling makes the vocabulary a type:
CREATE TYPE loan_status AS ENUM ('out', 'returned', 'lost');
CREATE TABLE loan_events (
event_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status loan_status NOT NULL
);
INSERT INTO loan_events (status) VALUES ('out'), ('returned');
INSERT INTO loan_events (status) VALUES ('misplaced');
CREATE TYPE
CREATE TABLE
INSERT 0 2
ERROR: invalid input value for enum loan_status: "misplaced"
LINE 1: INSERT INTO loan_events (status) VALUES ('misplaced');
^
Enum vs CHECK-on-text is a genuine judgment call: enums are self-documenting and compact, but changing the list is DDL (ALTER TYPE ... ADD VALUE — and removing a value is genuinely painful), while a CHECK is trivially replaceable. Stable vocabularies (weekdays, card suits) suit enums; evolving ones (order statuses, categories) usually suit a CHECK — or a reference table with a foreign key, which also lets you store facts about each status.
Domains — a named, reusable column type with rules baked in:
CREATE DOMAIN email_address AS text
CHECK (VALUE ~ '^[^@\s]+@[^@\s]+\.[^@\s]+$');
CREATE TABLE newsletter (
subscriber_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email email_address NOT NULL
);
INSERT INTO newsletter (email) VALUES ('[email protected]');
INSERT INTO newsletter (email) VALUES ('not-an-email');
CREATE DOMAIN
CREATE TABLE
INSERT 0 1
ERROR: value for domain email_address violates check constraint "email_address_check"
Define "what an email column is" once; every table that uses the domain enforces it identically. One rule, one place — Part 9's mantra, applied to types themselves.
🧪 Quick quiz — answer from memory, then check.
- Enum or CHECK for an evolving status vocabulary — and why?
- What problem do domains solve?
Show the answers
- CHECK (or a reference table): changing an enum's values is DDL, and removals are painful. Enums fit stable lists.
- A column rule written once and reused across tables — no copy-pasted CHECKs drifting apart.
Done here? The practice set for Part 10 — 6 exercises with solutions — is on the part page.