Sub topic 3
Domains, NULL, and NOT NULL
This chapter assumes you can write CREATE TABLE, INSERT, and SELECT statements, that you know the CHECK and NOT NULL constraints, and that you have a PostgreSQL database to test against.
Creating and using domains
A domain is a named base type with extra rules attached, such as a default, NOT NULL, and named CHECK constraints. Every column declared with the domain inherits those rules.
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
);
INSERT INTO customers (email) VALUES ('[email protected]');
INSERT INTO customers (email) VALUES ('not-an-email'); -- failsThe second insert fails because the value does not match the pattern. Inside a CHECK, VALUE stands for the value being tested.
NULL handling in domain constraints
A CHECK constraint passes when its expression is TRUE or NULL. A domain without NOT NULL therefore accepts NULL, even when the CHECK would reject every real value.
CREATE DOMAIN short_code AS text CHECK (length(VALUE) = 4);
SELECT NULL::short_code; -- returns NULL, no errorAdd NOT NULL to the domain to forbid NULL in every column that uses it.
Changing domain constraints safely
Adding a CHECK to a domain normally validates existing data at the moment you add it. Adding it as NOT VALID enforces the rule for new and updated values only. VALIDATE CONSTRAINT then checks the existing values as a separate step.
ALTER DOMAIN email_address
ADD CONSTRAINT email_address_max_length
CHECK (length(VALUE) <= 254) NOT VALID;
ALTER DOMAIN email_address VALIDATE CONSTRAINT email_address_max_length;Choosing between enums, domains, CHECK constraints, and lookup tables
| Requirement | Best fit |
|---|---|
| Fixed, ordered labels that rarely change | Enum |
| A reusable rule on a base type, such as email format | Domain |
| A one-off rule on one column | CHECK constraint |
| Values that users add or that carry extra data | Lookup table |
Exercise
A column stores a country code that must be exactly two uppercase letters and must never be NULL. Write the domain definition and state what the column rejects.
Show answer
CREATE DOMAIN countrycode AS text NOT NULL CHECK (VALUE ~ '^[A-Z]{2}$'); A column declared as countrycode rejects NULL and any value that is not two uppercase letters.