Sub topic 15
Domains and composite types
This chapter covers two ways to define your own types on top of existing ones. A domain adds rules to a single base type. A composite type groups several fields into one value. It assumes you know the built-in scalar types (integer, text, numeric), how CHECK and NOT NULL constraints work, and how to use CREATE TYPE for enums from the previous chapter.
Domains: a base type with rules attached
A domain is a named type built from another type, plus optional DEFAULT, NOT NULL and CHECK rules. Every column, function argument or variable that uses the domain enforces those rules. You write the rule once instead of repeating it on every column.
CREATE DOMAIN positive_int AS integer CHECK (VALUE > 0);
CREATE TABLE line_items (
order_id bigint NOT NULL,
quantity positive_int NOT NULL
);
INSERT INTO line_items VALUES (1, 3); -- works
INSERT INTO line_items VALUES (1, 0);
-- ERROR: value for domain positive_int violates check constraint "positive_int_check"Inside the CHECK, the keyword VALUE stands for the value being tested. PostgreSQL names an unnamed constraint <domain>_check. Give the constraint a name so the error message tells you what went wrong:
CREATE DOMAIN email_address AS text
CONSTRAINT email_has_at CHECK (VALUE ~ '^[^@\s]+@[^@\s]+$');What a domain does and does not change
- A domain is stored exactly like its base type.
positive_inttakes 4 bytes, the same asinteger. - Operators and functions for the base type work on the domain.
quantity + 1returns a plaininteger, so the result is no longer constrained. - The checks run when a value is assigned to something of the domain type: on insert, update, or a cast such as
5::positive_int. - A domain can be built on another domain. Constraints from every level apply.
NULL and domains
A CHECK passes when its expression evaluates to NULL, so a NULL value satisfies VALUE > 0. To reject NULLs, declare the domain NOT NULL, or put NOT NULL on each column as the example above does. Column-level NOT NULL is the safer habit. The PostgreSQL documentation warns that a domain's NOT NULL can be bypassed. For example, a left join can produce a NULL in a domain-typed column.
Changing a domain after it is in use
Changing a domain's rules affects every column that uses it, so existing data matters. ALTER DOMAIN ... ADD CONSTRAINT scans all tables using the domain and fails if any row violates the new rule. On large tables you can add the constraint as NOT VALID, then validate later:
ALTER DOMAIN email_address
ADD CONSTRAINT email_lowercase CHECK (VALUE = lower(VALUE)) NOT VALID;
-- New and updated values are checked now. Old rows are checked here:
ALTER DOMAIN email_address VALIDATE CONSTRAINT email_lowercase;NOT VALID skips the check of existing rows but still enforces the rule for new writes. VALIDATE CONSTRAINT fails if any old row breaks the rule, so you can fix the data first.
Composite types: several fields in one value
A composite type is a list of named fields, each with its own type. It works like a row without a table behind it.
CREATE TYPE address AS (
street text,
city text,
postal_code text
);
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
shipping address
);
INSERT INTO customers (name, shipping)
VALUES ('Ana', ROW('1 Main St', 'Leeds', 'LS1 4AP'));ROW(...) builds a composite value. The fields are matched by position, so the order must match the type definition.
Reading and updating fields
To read a field, wrap the column in parentheses. Without them, PostgreSQL reads shipping.city as column city of a table called shipping:
SELECT name, (shipping).city FROM customers; -- works
SELECT name, shipping.city FROM customers;
-- ERROR: missing FROM-clause entry for table "shipping"
SELECT (shipping).* FROM customers; -- expands to all three fieldsIn an UPDATE, you assign to a field without parentheses:
UPDATE customers SET shipping.city = 'York' WHERE name = 'Ana';Every table is also a composite type
Each table you create defines a composite type with the same name. You can select a whole row as one value, pass it to a function, or return it from one:
SELECT c FROM customers AS c; -- one column holding the whole rowNULL behaves differently for composites
IS NULL on a composite is true only when every field is NULL. IS NOT NULL is true only when every field is non-NULL. A row with some fields NULL is neither:
SELECT ROW(NULL, NULL) IS NULL AS all_null,
ROW(1, NULL) IS NULL AS partly_null_is_null,
ROW(1, NULL) IS NOT NULL AS partly_null_is_not_null;
-- all_null: true, partly_null_is_null: false, partly_null_is_not_null: falseSo a NOT NULL constraint on a composite column rejects only a NULL composite. It does not require the fields inside to be filled in.
Limits of composite columns
- You cannot put
CHECK,NOT NULLorDEFAULTon the fields inside a composite type. To enforce rules per field, give the field a domain type, such as anemail_addressfield. - Adding a field with
ALTER TYPE ... ADD ATTRIBUTEis possible, but it rewrites tables that use the type and can be slow. - Statistics and indexes work best on plain columns. Filtering on
(shipping).cityneeds an expression index, and the planner has little information about the individual fields. - Foreign keys cannot point at one field inside a composite.
Choosing between a domain, a composite and plain columns
| Need | Best fit | Reason |
|---|---|---|
| Same rule on many columns of one base type | Domain | One definition, one place to change |
| Values that always travel together and are queried as a unit | Composite | One value for function arguments and return values |
| Fields you filter, index, join on or constrain individually | Separate columns or a table | Full constraint, index and statistics support |
| A one-off rule on one column | Column `CHECK` | A domain adds indirection for no gain |
Common mistakes
- Expecting a domain's rule to survive arithmetic.
quantity - 5is aninteger, so a result below zero is not caught until you store it in a domain-typed column. - Forgetting the parentheses in
(col).field. - Treating a composite column like a mini table. If you need to search or join on its fields, a real table is the better design.
- Changing a domain on a large production table without
NOT VALID. The plain form scans every table that uses the domain.
Exercise
You define CREATE DOMAIN percentage AS numeric(5,2) CHECK (VALUE BETWEEN 0 AND 100); and a column discount percentage with no NOT NULL. Does INSERT ... VALUES (NULL) succeed? What query returns the city from a composite column shipping address in a table customers?
Show answer
The insert succeeds. The CHECK evaluates to NULL for a NULL value, and a NULL result counts as passing, so you need NOT NULL on the column or the domain to reject it. The city comes from SELECT (shipping).city FROM customers;. The parentheses are required, because shipping.city would be read as a table reference.
Exercise
What do ROW(1, NULL) IS NULL and ROW(1, NULL) IS NOT NULL return, and what does that mean for a NOT NULL constraint on a composite column?
Show answer
Both return false. IS NULL is true only when all fields are NULL, and IS NOT NULL is true only when all fields are non-NULL. A NOT NULL constraint on a composite column therefore rejects only a NULL composite value, and it does not require each field to be filled in. To enforce per-field rules, use domain types for the fields or separate columns.