Sub topic 7
Creating and Using Domains
A domain is a user-defined type built on top of an existing type. It carries its own default, NOT NULL setting, and CHECK constraints. You define the rules once, and every column, function parameter, or variable of that type follows them.
This chapter assumes you can write CREATE TABLE, INSERT, and SELECT, and that you know what CHECK and NOT NULL constraints do. You also need to be comfortable with built-in types such as text, numeric, and integer. It covers how to create a domain, how its constraints and defaults behave, and how to inspect and use it. The next chapters cover NULL semantics and changing a domain's constraints on a live system.
Why use a domain
Suppose five tables each store an email address. Without a domain, each table repeats the same CHECK expression. Over time the copies drift apart: one allows spaces, another has a typo in the regular expression, and a third has no check at all.
A domain fixes this by giving the rule a name and a single definition:
- The column declaration says what the data is (
email_address) instead of how it is stored (text). - A rule change happens in one place.
- Constraint names are stable and appear in error messages.
A domain does not create a new storage format. A value of a domain over text is stored exactly like text, with no extra bytes on disk. All the work happens when a value is converted to the domain type.
Creating a first domain
The basic form is CREATE DOMAIN name AS base_type, followed by optional DEFAULT, NOT NULL or NULL, and CHECK constraints.
CREATE DOMAIN email_address AS text
CONSTRAINT email_address_format
CHECK (VALUE ~* '^[^@[:space:]]+@[^@[:space:]]+$');This domain has one constraint, named email_address_format. Inside a domain's CHECK, the keyword VALUE stands for the value being tested. The regular expression requires one @, with at least one non-space character on each side and no whitespace anywhere. It is a sanity check, not a full implementation of the email standard.
The CONSTRAINT name part is optional. If you leave it out, PostgreSQL generates a name such as email_address_check. Name your constraints. The name shows up in error messages, and you need it later to alter or drop the constraint.
Using a domain as a column type
You use a domain anywhere you would use its base type. The second domain below adds DEFAULT and NOT NULL:
CREATE DOMAIN non_negative_money AS numeric(12,2)
DEFAULT 0
NOT NULL
CONSTRAINT non_negative_money_check CHECK (VALUE >= 0);
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]');
INSERT INTO customers (email) VALUES ('not-an-email');The first insert succeeds. The credit column is omitted, so it takes the domain default 0. The second insert fails:
ERROR: value for domain email_address violates check constraint "email_address_format"The message names the domain and the constraint, not the table. That is how you tell a domain violation from a table-level CHECK violation, which reads new row for relation "customers" violates check constraint ....
Because the base type is numeric(12,2), the domain inherits that precision and scale. Inserting 1.005 rounds to 1.01 before the check runs, and an insert of 10 billion or more fails with a numeric overflow error.
Where the checks run
PostgreSQL tests domain constraints whenever a value is converted to the domain type. Several operations cause that conversion:
INSERTandUPDATEinto a column of the domain type.- An explicit cast, such as
'x'::email_addressorCAST(expr AS email_address). - Passing an argument to a function parameter of the domain type, or returning a value from a function declared to return it.
- Assigning to a PL/pgSQL variable declared with the domain type.
Two details follow from this diagram. First, a bad value for the base type, such as 'abc' for a numeric domain, fails before any domain constraint runs. Second, a CHECK that evaluates to NULL counts as a pass. The next chapter explains the consequences.
The VALUE keyword and constraint rules
A domain CHECK expression can use only VALUE and constants or functions. It cannot refer to other columns or tables, and it cannot contain a subquery. If a rule needs data from another table, use a foreign key or a lookup table instead.
Keep the expression immutable, meaning the same input always gives the same result. A check that calls a volatile function, such as one that reads the current time, can make a dump and restore fail, because old rows no longer satisfy it.
Multiple constraints and their order
A domain can have several named CHECK constraints. PostgreSQL tests them in alphabetical order by name, and the first failure is the one you see.
CREATE DOMAIN us_zip AS text
CONSTRAINT a_digits_only CHECK (VALUE ~ '^[0-9]+$')
CONSTRAINT b_five_chars CHECK (length(VALUE) = 5);
SELECT 'abc'::us_zip; -- fails a_digits_only (b_five_chars would also fail)
SELECT '1234'::us_zip; -- fails b_five_chars
SELECT '02139'::us_zip; -- passesThe first query reports a_digits_only even though the value also breaks the length rule. If you want users to see the most useful message first, choose names that sort the way you want. Splitting a rule into several small named constraints gives clearer errors than one large expression.
Defaults and their precedence
A domain DEFAULT applies to any column of that type that has no default of its own. There are three levels, and the most specific one wins:
- A default on the column.
- A default on the domain.
- The base type's default, which is
NULL.
CREATE DOMAIN priority AS smallint
DEFAULT 3
CONSTRAINT priority_range CHECK (VALUE BETWEEN 1 AND 5);
CREATE TABLE tickets (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
severity priority,
escalation priority DEFAULT 5
);
INSERT INTO tickets DEFAULT VALUES;
SELECT severity, escalation FROM tickets;
-- severity = 3 (from the domain), escalation = 5 (from the column)The default expression is also tested against the domain's constraints when it is used. A default of 9 on this domain would let CREATE DOMAIN succeed but fail on the first insert that relies on it.
Domains in expressions
A domain value behaves like its base type in operators and functions. The result of an expression is the base type, not the domain, so the constraints are not applied again.
SELECT pg_typeof('[email protected]'::email_address);
-- email_address
SELECT pg_typeof('[email protected]'::email_address || '.uk'::text);
-- text
SELECT ('[email protected]'::email_address || '.uk'::text)::email_address;
-- passes: '[email protected]' still matches the pattern
SELECT ('[email protected]'::email_address || ' '::text)::email_address;
-- fails: the trailing space breaks email_address_formatIf you compute a value and store it in a domain column, the check runs at the assignment. If you only compute it and return it from a query, nothing checks it. Add an explicit cast when you want validation in a query.
Domains over other types
The base type of a domain can be almost any type, including arrays, composite types, enums, and other domains.
CREATE DOMAIN tag_list AS text[]
CONSTRAINT tag_list_max_five CHECK (cardinality(VALUE) <= 5);
CREATE DOMAIN company_email AS email_address
CONSTRAINT company_email_host CHECK (VALUE ~* '@example\.com$');
SELECT '[email protected]'::company_email; -- passes both domains' checks
SELECT '[email protected]'::company_email; -- fails company_email_host
SELECT ' [email protected]'::company_email; -- fails email_address_formatA domain built on another domain applies the parent's constraints and then its own. This lets you build a family of types from a general one, but it makes errors harder to trace. Keep the chain short.
A domain can also wrap an enum. That lets you restrict an enum to a subset of its labels, which an enum alone cannot do.
Inspecting domains
In psql, \dD lists domains, and \dD email_address shows one domain with its default, nullability, and checks. From SQL, two sources are useful:
SELECT conname, pg_get_constraintdef(oid) AS definition
FROM pg_constraint
WHERE contypid = 'email_address'::regtype
ORDER BY conname;
SELECT domain_name, data_type, domain_default
FROM information_schema.domains
WHERE domain_schema = 'public'
ORDER BY domain_name;The first query reads the system catalog pg_constraint, where domain constraints use the contypid column instead of conrelid. The second uses the standard information_schema view, which is easier to read but exposes fewer details.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `value for domain ... violates check constraint "..."` | Data fails a domain `CHECK` | Fix the data, or relax the named constraint |
| `domain ... does not allow null values` | An explicit `NULL` was sent to a domain declared `NOT NULL` | Send a real value, or use `DEFAULT` by omitting the column |
| `cannot use subquery in check constraint` | The `CHECK` refers to a table | Use a foreign key or a lookup table |
| `cannot drop type ... because other objects depend on it` | Columns or functions use the domain | Change those objects first |
| Constraint seems to be skipped in a query | The expression result is the base type | Add an explicit cast to the domain |
Summary
- A domain wraps a base type with a default,
NOT NULL, and namedCHECKconstraints. VALUEin aCHECKis the value under test. The expression cannot use subqueries or other columns.- Checks run on conversion to the domain type: inserts, updates, casts, and function arguments and results.
- Several
CHECKconstraints are tested alphabetically by name. - A column default overrides a domain default, which overrides the base type's
NULL. - Expressions on domain values return the base type, so cast back to re-validate.
Exercise
Create a domain percentage over numeric(5,2) with a default of 0 and a constraint named percentage_range that allows only values from 0 to 100. Then create a table survey_answers with a score column of that type and a weight column of that type with its own default of 50. If you run INSERT INTO survey_answers DEFAULT VALUES, what values do score and weight get?
Show answer
The definitions are CREATE DOMAIN percentage AS numeric(5,2) DEFAULT 0 CONSTRAINT percentage_range CHECK (VALUE BETWEEN 0 AND 100); and CREATE TABLE survey_answers (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, score percentage, weight percentage DEFAULT 50);. The insert gives score = 0, taken from the domain default, and weight = 50, because the column default overrides the domain default.
Exercise
A domain us_zip has two constraints, a_digits_only (digits only) and b_five_chars (length 5). You run SELECT 'ab'::us_zip;. Which constraint name appears in the error, and why? Then explain why SELECT ('02139'::us_zip || 'x'::text)::us_zip; fails but SELECT '02139'::us_zip || 'x'::text; succeeds.
Show answer
The error names a_digits_only, because PostgreSQL tests domain CHECK constraints in alphabetical order by name and stops at the first failure, even though ab also breaks the length rule. The first expression fails because the concatenation returns plain text (02139x), and the explicit cast back to us_zip runs the checks, which the six-character, non-digit string breaks. The second expression has no cast to the domain, so no domain constraint is evaluated and it returns 02139x as text.