Sub topic 10
Choosing between enums, domains, CHECK constraints, and lookup tables
This chapter assumes you know CREATE TABLE, INSERT, SELECT, and WHERE. It also assumes you know CHECK and NOT NULL constraints and basic foreign keys. It builds on the earlier chapters of this tutorial: enum ordering and ALTER TYPE, the type-replacement workaround for removing values, and domain NULL behavior with NOT VALID.
PostgreSQL gives you four ways to restrict what a column can hold:
- an enum type
- a domain over a base type
- a
CHECKconstraint written directly on the column - a lookup table referenced by a foreign key
All four reject bad values. They differ in how much it costs to change the allowed set, what extra data they can carry, and how well they travel through tools such as ORMs, dumps, and replication. This chapter compares them on the points that decide the choice.
The same rule, four ways
The following script implements one rule, "a ticket is open or closed", with each mechanism. You can run it as shown in psql.
-- 1. Enum
CREATE TYPE ticket_status AS ENUM ('open', 'closed');
CREATE TABLE ticket_enum (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status ticket_status NOT NULL DEFAULT 'open'
);
-- 2. Column CHECK constraint
CREATE TABLE ticket_check (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status text NOT NULL DEFAULT 'open'
CONSTRAINT ticket_check_status CHECK (status IN ('open', 'closed'))
);
-- 3. Domain
CREATE DOMAIN ticket_state AS text
CONSTRAINT ticket_state_values CHECK (VALUE IN ('open', 'closed'));
CREATE TABLE ticket_domain (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status ticket_state NOT NULL DEFAULT 'open'
);
-- 4. Lookup table with a foreign key
CREATE TABLE ticket_status_ref (
code text PRIMARY KEY,
label text NOT NULL,
sort_order integer NOT NULL,
is_active boolean NOT NULL DEFAULT true
);
INSERT INTO ticket_status_ref (code, label, sort_order)
VALUES ('open', 'Open', 1), ('closed', 'Closed', 2);
CREATE TABLE ticket_lookup (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status text NOT NULL DEFAULT 'open' REFERENCES ticket_status_ref (code)
);Each table rejects INSERT ... VALUES ('archived'), but the error differs. The enum reports invalid input value for enum ticket_status. The CHECK and the domain report a constraint violation by name. The lookup table reports a foreign key violation. The enum fails while the literal is being converted to the type, so it never reaches the constraint checks.
Adding a value
Suppose the business adds an on_hold state. This change happens more often than any other, and the four mechanisms handle it differently.
-- Enum: one statement, no table scan, position chosen by you
ALTER TYPE ticket_status ADD VALUE IF NOT EXISTS 'on_hold' AFTER 'open';
-- CHECK: replace the constraint; NOT VALID avoids a long exclusive scan
ALTER TABLE ticket_check
DROP CONSTRAINT ticket_check_status,
ADD CONSTRAINT ticket_check_status
CHECK (status IN ('open', 'on_hold', 'closed')) NOT VALID;
ALTER TABLE ticket_check VALIDATE CONSTRAINT ticket_check_status;
-- Domain: same idea, but the change applies to every column using the domain
BEGIN;
ALTER DOMAIN ticket_state DROP CONSTRAINT ticket_state_values;
ALTER DOMAIN ticket_state
ADD CONSTRAINT ticket_state_values
CHECK (VALUE IN ('open', 'on_hold', 'closed')) NOT VALID;
COMMIT;
ALTER DOMAIN ticket_state VALIDATE CONSTRAINT ticket_state_values;
-- Lookup table: ordinary data change
INSERT INTO ticket_status_ref (code, label, sort_order)
VALUES ('on_hold', 'On hold', 2);Notes on the comparison:
- The enum is a schema change, so it needs a migration. It is cheap, but the new label cannot be used in the same transaction that added it. Plan for two deploy steps if your migration tool wraps everything in one transaction.
- The
CHECKand the domain follow a drop-and-re-add pattern. Dropping and adding inside one transaction avoids a window with no rule. Adding asNOT VALIDmakes new writes obey the rule at once, andVALIDATE CONSTRAINTchecks old rows with a weaker lock. You can skipNOT VALIDon small tables, but a plainADD CONSTRAINTscans the whole table under an exclusive lock. - With a domain, the constraint change reaches every table that uses the domain. That is the point of a domain, and it is also why validation can be slow if the domain is used widely.
- The lookup table change is an
INSERT. It is transactional, takes effect immediately, needs noALTER, and can be done by an application with data-level permissions only.
Renaming and removing values
| Operation | Enum | CHECK on text | Domain over text | Lookup table |
|---|---|---|---|---|
| Rename a value | `ALTER TYPE ... RENAME VALUE`, stored rows untouched | `UPDATE` all rows and replace the constraint | Same as `CHECK`, across every using table | Change `label` freely. Changing `code` needs `ON UPDATE CASCADE` or a surrogate key |
| Remove a value | No direct way. Replace the type (table rewrite, exclusive lock) | Migrate rows, then replace the constraint | Migrate rows in every using table, then replace the constraint | Migrate rows, then `DELETE`, or set `is_active = false` |
| Reorder or insert in the middle | `ADD VALUE ... BEFORE/AFTER` | Order is not part of the type | Order is not part of the type | Change `sort_order` |
Removal is the clearest weakness of enums. If you expect values to be retired, the type-replacement procedure from the earlier chapter is a heavy price to pay each time. A lookup table with an is_active flag handles retirement without any schema change.
What each mechanism can carry
An enum value is only a label with a position. A lookup table row can carry anything: a display name, a description, a color, a sort order, an effective date, or a flag such as is_terminal. If the application needs to list the allowed values with metadata, the lookup table is the only option that stores it in the database. With an enum you must keep that data in application code or in a separate table keyed by label, which brings back the lookup table anyway.
Enums have one property the others lack: a declared, built-in order. ORDER BY status and status >= 'paid' use declaration order, and enum_range lists the values. With text columns you would sort alphabetically, which is rarely what you want. With a lookup table you must join to the table to sort by sort_order.
A domain has a property that enums and lookup tables lack. It can restrict the shape of a value over any base type, not just a list of labels. Examples are an email format, a non-negative numeric(12,2), or a four-character code. It also bundles a default and NOT NULL with the rule. Write the rule once and reuse it in every table.
A CHECK on the table is the only mechanism that can see more than one column. A domain constraint can reference only VALUE. A rule like CHECK (ended_at IS NULL OR ended_at >= started_at) belongs in a table constraint.
CREATE TABLE subscriptions (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
started_at timestamptz NOT NULL,
ended_at timestamptz,
CONSTRAINT subscriptions_period_valid
CHECK (ended_at IS NULL OR ended_at >= started_at)
);Storage, performance, and tooling
| Concern | Enum | CHECK on text | Domain | Lookup table |
|---|---|---|---|---|
| Storage per value | 4 bytes | Length of the string plus header | Same as the base type | FK column of the key type (text, or 4 bytes for an integer key) |
| Write overhead | Type conversion only | Evaluating the expression | Evaluating the expression | Foreign key check, which does an index lookup |
| Readable in raw output | Yes, shown as the label | Yes | Yes | Only if the key is a readable code. An integer key needs a join |
| Needs a join to show a label | No | No | No | Yes, if the label differs from the code |
| Visible in the catalog | `pg_type`, `pg_enum` | `pg_constraint` | `pg_type`, `pg_constraint` | Ordinary table |
The storage differences are small. Do not pick a mechanism for space reasons unless you have millions of rows and have measured it. Enum labels are limited to 63 bytes. Text keys have no such limit.
Tooling is more likely to affect your decision than storage:
- Logical replication does not replicate DDL. A new enum value or a changed domain constraint must be applied on each subscriber, and enum values must exist there before rows that use them arrive. A lookup table row is ordinary data and replicates normally.
- Drivers and ORMs vary in how they map enums. Some treat them as unknown types, so you may need explicit casts such as
$1::ticket_status. Text columns withCHECKconstraints and lookup keys cause no such problems. - Operators and functions for text do not work directly on enums.
status LIKE 'op%'fails until you writestatus::text LIKE 'op%'. Two different enum types also cannot be compared with each other.
Decision guide
The diagram summarizes the questions to ask, in the order that usually settles it.
Apply these rules of thumb:
- Use an enum when the set is small, closed, and changes rarely, such as days of the week, severity levels, or a short state machine. Pick an enum especially when the order matters for sorting or range comparisons. Be ready to run a migration when it changes, and avoid enums for values you will want to retire.
- Use a lookup table when the set is open-ended, edited by non-developers, needs display names or flags, needs soft retirement, or is referenced by many other systems. Countries, product categories, and currencies are typical. You pay a join and a foreign key check.
- Use a domain when the rule describes what a valid value looks like, for example emails, postal codes, percentages, or non-negative money. Use it when the same rule appears in many columns. A domain over an enum or a text list is also possible, but an enum or lookup table is usually clearer for that job.
- Use a plain
CHECKconstraint for rules that appear once, rules that involve several columns, and small value lists that you are happy to rewrite with a one-line migration. ACHECKis the lowest-ceremony option and needs no new object.
Combinations are common and fine. A domain such as non_negative_money can sit in a table that also uses an enum for status and a lookup table for category. You can also combine a domain with a lookup table by giving the foreign key column a domain type that enforces the code format.
Common mistakes
- Choosing an enum for a list that will keep changing. The cost shows up when the first value must be removed, or when a migration tool runs
ADD VALUEand a later statement in the same transaction uses it. - Forgetting that
NULLpasses constraints. A nullable column using a domain orCHECKstill acceptsNULL. AddNOT NULLto the column or the domain if you need a value. A foreign key also skipsNULLvalues. - Putting a subquery or another table's data in a
CHECK. PostgreSQL does not allow subqueries inCHECKconstraints. A function that reads another table in aCHECKis accepted but is not rechecked when that other table changes, so the rule can silently stop being true. Use a foreign key instead. - Adding a domain constraint without
NOT VALIDon a big system. The plain form scans every table using the domain while holding a strong lock. - Using integer codes in a lookup table with no readable form. Queries and ad hoc reports then need joins to be understood. Use a text code as the key unless you have a reason to use a surrogate key.
Exercises
Exercise
A product team wants a priority column with values low, medium, high, and urgent. Reports must sort by priority and filter with priority >= 'high'. The list has not changed in five years. Which mechanism fits best, and what is the main cost you accept?
Show answer
An enum type declared in the order low, medium, high, urgent. It gives sorting and range comparisons by declaration order with 4 bytes of storage. The cost is that adding a value needs a schema migration (and the new value cannot be used in the transaction that adds it), and removing a value needs a full type replacement.
Exercise
You need the same "valid email, at most 254 characters" rule on customers.email, suppliers.contact_email, and invoices.billing_email. Which mechanism avoids repeating the rule, and how would you tighten it later on a live system without a long exclusive scan?
Show answer
A domain, for example email_address AS text with a named CHECK. To tighten it, run ALTER DOMAIN email_address ADD CONSTRAINT ... CHECK (...) NOT VALID, which enforces the rule for new writes immediately. Then run ALTER DOMAIN email_address VALIDATE CONSTRAINT ... to check existing rows with a weaker lock.
Exercise
Support staff need to add and retire ticket categories from an admin screen, and each category has a display name and a color. Why is a lookup table a better choice than an enum or a domain here? Write the column definition on tickets that enforces it.
Show answer
Staff change the set as data without a schema migration, and a lookup table can store the display name, color, and an is_active flag. An enum holds only labels and cannot drop values easily. The column is category text NOT NULL REFERENCES ticket_category (code), with ticket_category holding code, label, color, and is_active.
Exercise
A table must satisfy "if status is shipped, then shipped_at must not be NULL". Can a domain enforce this? What should you use?
Show answer
No. A domain constraint can see only VALUE, the single value being checked, so it cannot compare two columns. Use a table-level constraint such as CHECK (status <> 'shipped' OR shipped_at IS NOT NULL).