Sub topic 10
Choosing Between Enums, Domains, CHECK Constraints, and Lookup Tables
This chapter assumes you know basic PostgreSQL table definitions, INSERT, SELECT, WHERE, CHECK, NOT NULL, and foreign keys. It also assumes you understand that a foreign key requires a value to exist in another table.
PostgreSQL gives you several ways to restrict column values. The best choice depends on whether the allowed values are fixed, whether the rule applies to one type across many tables, and whether the values need their own data or relationships.
The four approaches
A PostgreSQL enum is a type containing a fixed, ordered list of labels. A domain is a type based on another type, such as text or numeric, with reusable constraints. A CHECK constraint validates values directly on a table or column. A lookup table stores allowed values as rows and usually connects to them with a foreign key.
| Approach | Best fit | Main strength | Main limitation |
|---|---|---|---|
| Enum | A small, stable set of application states | Strong type checking and compact SQL | Removing or freely changing values is difficult |
| Domain | One reusable rule for a base type | Centralizes validation across columns | It cannot easily express relationships to other rows |
| `CHECK` constraint | A rule specific to one table or column | Simple and flexible | Reuse requires repeating or carefully managing the rule |
| Lookup table | Values have descriptions, ownership, or lifecycle | Data can change through normal row operations | Requires a table, foreign key, and joins |
Use an enum for stable application states
Enums work well when the labels are part of the database design and are unlikely to change often. For example, an order may have a small set of states:
CREATE TYPE order_status AS ENUM (
'pending',
'paid',
'shipped',
'delivered',
'cancelled'
);
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status order_status NOT NULL DEFAULT 'pending'
);The status column accepts only labels from order_status. The database rejects arbitrary text such as 'unknown'.
Enums also define an order. The order is the declaration order, not alphabetical order:
SELECT id, status
FROM orders
WHERE status >= 'paid' AND status < 'delivered'
ORDER BY status;This ordering can be useful, but it can also create surprising behavior if readers assume normal text ordering.
You can add a value with ALTER TYPE and rename a value without rewriting stored rows. However, enum changes are schema changes. A newly added value may not be usable in the same transaction that added it, depending on the PostgreSQL version and transaction context. Migration tools should therefore run the addition and later use of the value in separate migration steps when required.
Enums are a poor fit when administrators need to add, disable, describe, or reorder options frequently. They are also a poor fit when removing a value is a normal operation. PostgreSQL does not provide a direct command to drop one enum label. Removing one requires replacing the type and converting the columns.
Use a domain for a reusable type rule
A domain wraps a base type with shared rules. Use one when multiple columns should obey the same definition.
CREATE DOMAIN email_address AS text
CONSTRAINT email_address_format
CHECK (VALUE ~* '^[^@[:space:]]+@[^@[:space:]]+$');
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email email_address NOT NULL
);Every column declared as email_address receives the domain's format rule. The column's own NOT NULL requirement remains separate. A domain can also define DEFAULT and NOT NULL, but use those rules deliberately because they affect every column using the domain.
Domains are useful for values such as email-like text, non-negative money, international codes, or bounded measurements. They are less suitable when validation needs another row, such as checking that a category exists in a business-managed list. A domain constraint cannot replace a foreign key relationship.
Use a CHECK constraint for local rules
A CHECK constraint is usually the clearest choice when a rule belongs to one table.
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku text NOT NULL,
price numeric(12, 2) NOT NULL
CHECK (price >= 0),
stock_count integer NOT NULL
CHECK (stock_count >= 0)
);This keeps the rule next to the data it protects. It is a good fit for bounds, formats, and relationships among columns in the same row. A table-level check can compare columns:
CREATE TABLE reservations (
starts_at timestamptz NOT NULL,
ends_at timestamptz NOT NULL,
CHECK (ends_at > starts_at)
);A CHECK expression passes when it evaluates to TRUE or NULL. If a nullable column must satisfy a rule whenever it has a value, this may be correct. If the column must always contain a valid value, add NOT NULL.
Use a lookup table for changing or descriptive values
A lookup table is the right choice when allowed values are data rather than fixed schema labels.
CREATE TABLE order_statuses (
code text PRIMARY KEY,
display_name text NOT NULL,
is_active boolean NOT NULL DEFAULT true
);
INSERT INTO order_statuses (code, display_name)
VALUES
('pending', 'Pending'),
('paid', 'Paid'),
('shipped', 'Shipped');
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status_code text NOT NULL
REFERENCES order_statuses (code)
);A lookup row can have descriptions, sort positions, translations, permissions, effective dates, or an active flag. You can add or deactivate a value with ordinary INSERT and UPDATE statements. A foreign key also gives you referential integrity: an order cannot reference a status code that does not exist.
The trade-off is operational complexity. Queries may need joins, and deletion or renaming must account for existing references. In many systems, marking a lookup value inactive is safer than deleting it.
A practical decision process
Use these questions in order:
- Is the rule specific to one table or row? Start with a
CHECKconstraint. - Should the same base-type rule apply to many columns? Consider a domain.
- Is the set small, ordered, and controlled by schema migrations? Consider an enum.
- Do values need descriptions, metadata, activation states, or foreign-key relationships? Use a lookup table.
- Will values be removed, renamed, or added regularly? Prefer a lookup table or, for simple local rules, a
CHECKconstraint. - Does the application need database-enforced referential integrity? Use a lookup table with a foreign key.
The choice is not permanent in theory, but changing a type used throughout a production system can require migrations and coordinated application changes. Decide based on the expected rate of change, the importance of metadata, and whether the rule is local or shared.
Exercise
A support system has ticket priorities of low, medium, and high. Each priority needs a display label, a numeric sort order, translations, and an active flag. Should priorities be an enum, domain, CHECK constraint, or lookup table?
Show answer
Use a lookup table with a foreign key. The priorities have metadata and may need to be changed or deactivated without changing the database type.