Sub topic 7
Creating and using domains
A domain is a PostgreSQL type built on top of an existing base type. It lets you define a reusable set of rules for values such as email addresses, positive quantities, or non-negative money.
This chapter assumes that you know CREATE TABLE, INSERT, SELECT, WHERE, CHECK, NOT NULL, DEFAULT, and the basic idea of foreign keys.
The domain working model
A domain has:
- A base type, such as
text,integer, ornumeric(12,2). - An optional default value.
- An optional
NOT NULLrule. - Zero or more named
CHECKconstraints.
Every column that uses the domain gets the domain's rules. This avoids copying the same validation expression into many tables.
flowchart TD
A[Value assigned to a column] --> B[Base type conversion]
B --> C[Domain default if no value was supplied]
C --> D[Domain NOT NULL rule]
D --> E[Domain CHECK constraints]
E --> F[Stored column value]A domain does not create a separate storage format. A column using non_negative_money is stored like its underlying numeric(12,2) type. The domain adds rules around that value.
Defining a domain
The following domain accepts text that contains an @ character with non-space text on both sides.
CREATE DOMAIN email_address AS text
CONSTRAINT email_address_format
CHECK (VALUE ~* '^[^@[:space:]]+@[^@[:space:]]+$');VALUE means the value being checked. The ~* operator performs a case-insensitive regular-expression match. The constraint has a name, email_address_format, so PostgreSQL can report a useful name when an insert fails.
A second domain shows all three common options:
CREATE DOMAIN non_negative_money AS numeric(12,2)
DEFAULT 0
NOT NULL
CONSTRAINT non_negative_money_check CHECK (VALUE >= 0);This domain:
- Uses
numeric(12,2)as its base type. - Uses
0when a value is omitted and no table-level default replaces it. - Rejects
NULL. - Rejects negative values.
You can use domains in table definitions just like built-in types.
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email email_address NOT NULL,
credit non_negative_money
);
INSERT INTO customers (email) VALUES ('[email protected]');
SELECT id, email, credit
FROM customers;The first insert omits credit. Because the column has no table-level default, the domain default supplies 0.
How validation is applied
PostgreSQL checks the base type and then checks the domain constraints. An invalid value fails before it is stored.
INSERT INTO customers (email, credit)
VALUES ('[email protected]', 25.50);
INSERT INTO customers (email, credit)
VALUES ('[email protected]', -4.00);The first insert succeeds. The second insert fails because -4.00 violates non_negative_money_check.
An invalid email also fails:
INSERT INTO customers (email, credit)
VALUES ('not-an-email', 10.00);The error identifies the domain constraint that failed. The same validation applies to every column that uses email_address.
You can explicitly cast a value to a domain type:
SELECT '[email protected]'::email_address;
SELECT 12.50::non_negative_money;Explicit casts are useful for testing a domain or for making the expected type clear in an expression.
Domain rules and table rules
A domain rule belongs to the type. A table constraint belongs to one table and often refers to other columns.
For example, the domain can require a non-negative credit value:
CREATE TABLE accounts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
credit non_negative_money
);A table can add a rule about the meaning of that value:
ALTER TABLE accounts
ADD CONSTRAINT credit_requires_account
CHECK (credit IS NULL OR id IS NOT NULL);In practice, the table rule might compare two columns, while the domain rule validates one value wherever the domain is used.
A domain is a good fit when the same single-value rule appears across several tables. A table CHECK is usually clearer when the rule is specific to one table or compares multiple columns.
Common errors
Expecting a domain to validate `NULL`
A CHECK constraint passes when its expression returns either TRUE or NULL. Therefore, this domain does not reject NULL:
CREATE DOMAIN short_code AS text
CONSTRAINT short_code_length
CHECK (length(VALUE) = 4);
SELECT NULL::short_code;length(NULL) returns NULL, so the check result is NULL, and the cast succeeds.
Add NOT NULL when the domain itself must reject NULL:
CREATE DOMAIN required_short_code AS text
NOT NULL
CONSTRAINT required_short_code_length
CHECK (length(VALUE) = 4);A table column can also add NOT NULL separately. The difference is scope: a domain-level rule applies to every use of the domain, while a column-level rule applies only to that column.
Confusing a domain with an enum
An enum is a closed list of named labels, such as pending and paid. A domain is a constrained version of a base type. A domain over text can accept many strings if its checks allow them; it does not automatically define a fixed list.
Hiding important table semantics in a domain
A domain should express a reusable property of one value. Do not use it to hide rules that depend on a particular table, another column, or a foreign-key relationship. Those rules belong in the table definition or in related tables.
Choosing a domain
Use a domain when all of these are true:
- The rule applies to one value.
- The rule is reused across multiple columns or tables.
- The base type already matches the required storage and operators.
- The rule should remain consistent wherever the domain is used.
Use a plain CHECK constraint when the rule is local to one table. Use a lookup table when valid values are business data that need descriptions, ownership, effective dates, or foreign-key references.
Exercise
Why does SELECT NULL::short_code succeed for a domain defined only with CHECK (length(VALUE) = 4), and how can the domain reject NULL?
Show answer
The check expression returns NULL for a NULL input, and a CHECK constraint passes when its result is TRUE or NULL. Add NOT NULL to the domain, or add NOT NULL to the particular table column.