Sub topic 8
Domains, NULL, and NOT NULL
This chapter assumes you can write CREATE TABLE, INSERT, SELECT, and WHERE. You should also know what CHECK and NOT NULL constraints do on a table, and that SQL uses three-valued logic: a condition can be true, false, or unknown. The previous chapter showed how to create a domain. This one covers how domains treat NULL, because that is where most surprises come from.
The rule: CHECK passes on NULL
A domain is a base type plus optional DEFAULT, NOT NULL, and CHECK rules. A CHECK constraint in a domain follows the same rule as a CHECK constraint on a table. The value is rejected only when the expression evaluates to false. If the expression evaluates to true or to NULL (unknown), the value is accepted.
This differs from WHERE, which keeps a row only when the condition is true.
| Expression result | `WHERE` clause | `CHECK` constraint (table or domain) |
|---|---|---|
| true | row kept | value accepted |
| false | row dropped | value rejected |
| NULL | row dropped | value accepted |
Here is the email domain from the earlier chapter:
CREATE DOMAIN email_address AS text
CONSTRAINT email_address_format
CHECK (VALUE ~* '^[^@[:space:]]+@[^@[:space:]]+$');
SELECT NULL::email_address;The SELECT returns NULL without an error. Inside the check, VALUE is NULL, and NULL ~* 'pattern' is NULL, not false. The constraint cannot reject unknown results, so the value passes.
The same thing happens with any CHECK that does arithmetic or comparison on VALUE:
CREATE DOMAIN short_code AS text CHECK (length(VALUE) = 4);
SELECT NULL::short_code;length(NULL) is NULL, so NULL = 4 is NULL, and the cast succeeds. A domain that restricts the shape of a value does not, by itself, restrict whether a value exists.
The following diagram shows the order of the checks when a value is converted to a domain type.
NULL can also appear inside a non-NULL value
The CHECK expression can evaluate to NULL even when the value itself is not NULL. This happens when the expression reaches into a value that holds a NULL, such as an array element.
CREATE DOMAIN positive_first AS integer[]
CHECK (VALUE[1] > 0);
SELECT ARRAY[5, -1]::positive_first; -- accepted: VALUE[1] is 5
SELECT ARRAY[-5, 1]::positive_first; -- ERROR: VALUE[1] > 0 is false
SELECT ARRAY[NULL, 5]::positive_first; -- accepted: VALUE[1] > 0 is NULLThe third query passes even though the array is not NULL. Empty arrays behave similarly with array_length(VALUE, 1), which returns NULL for an empty array.
When a constraint must reject unknown results, make the expression return a definite answer. One way is to wrap it in COALESCE:
CREATE DOMAIN strict_positive_first AS integer[]
CHECK (COALESCE(VALUE[1] > 0, false));With this version, ARRAY[NULL, 5] is rejected because the COALESCE turns the unknown result into false. Notice that NULL::strict_positive_first is now also rejected: VALUE[1] is NULL, COALESCE returns false, and the check fails. A COALESCE(..., false) check therefore also blocks a plain NULL value. If you want that, say it with NOT NULL instead and keep the CHECK readable.
Adding NOT NULL to a domain
To reject NULL values outright, declare the domain NOT NULL. You can combine it with DEFAULT and named CHECK constraints:
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, credit) VALUES ('[email protected]', NULL);The first INSERT succeeds. The credit column is not mentioned, so it takes the domain's default of 0. The second INSERT fails with domain non_negative_money does not allow null values (SQLSTATE 23502, not_null_violation). The credit column in customers has no NOT NULL of its own, but the domain supplies the rule.
Casting a literal NULL fails the same way:
SELECT NULL::non_negative_money;This raises the same error. With a NOT NULL domain you cannot even write a typed NULL of that type, which can get in the way of generic code, such as a function that returns the domain type and sometimes has nothing to return.
Domain NOT NULL versus column NOT NULL
You have two places to say "this value is required":
- On the domain:
CREATE DOMAIN ... NOT NULL. - On the column:
email email_address NOT NULL.
Both stop an INSERT or UPDATE from storing NULL. They differ in scope and in what error you get.
| Aspect | Domain `NOT NULL` | Column `NOT NULL` |
|---|---|---|
| Applies to | Every use of the type: columns, casts, function arguments and results | One column |
| Reusable | Yes, written once | Repeat on every column |
| Error message | `domain ... does not allow null values` | `null value in column "..." violates not-null constraint` |
| Nullable columns of the type | Not possible | Possible on other columns |
| Typed `NULL` casts | Fail | Succeed |
The two messages also tell you which rule fired. The column version names the table and column, which is more useful in application logs.
The usual recommendation is to keep domains nullable and put NOT NULL on columns. Requiredness is normally a property of a column, not of a type. An email_address is a required value in customers and optional in contact_preferences. If the domain carries NOT NULL, the optional use becomes awkward or impossible. Use NOT NULL in the domain only when a value of that type is meaningless without a value, such as the non_negative_money example where 0 is a natural stand-in for "nothing".
Changing the setting later is possible. ALTER DOMAIN ... SET NOT NULL checks every column that uses the domain and fails if any holds a NULL. DROP NOT NULL only relaxes the rule.
ALTER DOMAIN short_code SET NOT NULL;
ALTER DOMAIN short_code DROP NOT NULL;SET NOT NULL has to scan every table with a column of that type, so it can take a while on large tables and holds locks while it does. If you need to enforce requiredness on a big table with little downtime, the column-level NOT NULL is not much cheaper (it also scans), but you control it per table.
Where domain NOT NULL does not hold
The PostgreSQL documentation warns that a domain's NOT NULL is checked when a value is converted to the domain type. It is not an invariant of every value of that type. A value can read as NULL even though its type says NOT NULL.
The first case is an outer join. Rows that find no match are filled with NULL, and no conversion happens:
SELECT c.id, p.credit
FROM customers AS c
LEFT JOIN (SELECT id, credit FROM customers WHERE false) AS p
ON p.id = c.id;The credit column in the result has type non_negative_money and contains NULL for every row.
The second case is a scalar subquery that returns no rows. Its result is NULL and is already considered to be of the domain type, so PostgreSQL does not check it again:
INSERT INTO customers (email, credit)
VALUES ('[email protected]', (SELECT credit FROM customers WHERE false));This statement succeeds and stores NULL in credit, even though the domain forbids it. The stored NULL is now in the table.
This matters for how you design. When a column must never contain NULL, add NOT NULL to the column as well:
CREATE TABLE accounts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
credit non_negative_money NOT NULL
);A column-level constraint is enforced on every write to the table. The domain's NOT NULL then adds nothing for storage but still affects casts and function results. It also means application code reading query results cannot assume a non_negative_money value is never NULL.
Defaults and NULL
A domain can carry a DEFAULT. When a column of that domain type has no default of its own, the column inherits the domain's default. That is why the first INSERT into customers stored 0 in credit.
A column-level default overrides the domain default:
CREATE TABLE gift_cards (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
credit non_negative_money DEFAULT 25
);
INSERT INTO gift_cards DEFAULT VALUES;
SELECT credit FROM gift_cards;The query returns 25. Defaults apply only when the column is omitted or you write DEFAULT. They do not turn an explicit NULL into the default. In INSERT INTO gift_cards (credit) VALUES (NULL), the NULL is an explicit value, so it is rejected by the NOT NULL domain. Without NOT NULL it would be stored as NULL.
A common pairing is DEFAULT plus NOT NULL in the domain, as non_negative_money does. A nullable domain with a default is also common. In that case omitted columns get the default, and explicit NULLs still go through.
Checking what a domain actually enforces
Because of these rules, it helps to confirm what a domain does before relying on it. In psql, \dD lists domains and \dD+ email_address shows details. You can also query the catalogs:
SELECT typname, typnotnull, typdefault
FROM pg_type
WHERE typtype = 'd'
AND typname IN ('email_address', 'non_negative_money', 'short_code');
SELECT conname, pg_get_constraintdef(oid) AS definition
FROM pg_constraint
WHERE contypid = 'non_negative_money'::regtype;The first query shows whether NOT NULL is set and what the default expression is. The second lists the named CHECK constraints on a domain. Domain constraints are in pg_constraint with contypid set, not conrelid.
Common errors
- Assuming a CHECK rejects NULL.
CHECK (length(VALUE) = 4)acceptsNULL. AddNOT NULLto the column or domain. - Putting NOT NULL on a general-purpose domain. Every user of the type inherits it, and casts such as
NULL::the_domainstart to fail. Prefer column-levelNOT NULL. - Trusting query results. A column of a
NOT NULLdomain type can still beNULLin a join result. HandleNULLin code that consumes outer-join output. - Expecting the default to replace an explicit NULL. Defaults apply only to omitted values.
- Using SET NOT NULL on a populated column type without checking.
ALTER DOMAIN ... SET NOT NULLfails if any existing row holdsNULL. Find them first with a query such asSELECT count(*) FROM customers WHERE credit IS NULL. - Writing checks that depend on NULL by accident. A
CHECKover arrays, composites, or functions that returnNULLfor some inputs may pass values you meant to reject. Test withNULL, an empty value, and a value containingNULL.
Exercises
Exercise
Given CREATE DOMAIN short_code AS text CHECK (length(VALUE) = 4);, what do SELECT 'abcd'::short_code, SELECT 'abc'::short_code, and SELECT NULL::short_code each return?
Show answer
The first returns abcd. The second fails with an error that the value violates the check constraint short_code_check, because length('abc') = 4 is false. The third returns NULL, because length(NULL) = 4 evaluates to NULL, and a CHECK accepts NULL results.
Exercise
A table has code short_code NOT NULL and another table has code short_code with no NOT NULL. You want to make short_code reject NULL everywhere. What command do you run, what happens if the second table already contains NULL codes, and what is the downside of this approach?
Show answer
Run ALTER DOMAIN short_code SET NOT NULL;. It checks every column that uses the domain, so it fails if the second table holds any NULL code, and you must fix or remove those rows first. The downside is that the domain is now required everywhere: typed casts of NULL to short_code fail, and no column of that type can ever be optional. Putting NOT NULL on only the columns that need it is more flexible.
Exercise
A column credit non_negative_money (a NOT NULL domain, no column-level NOT NULL) contains a NULL after an INSERT that used a scalar subquery returning no rows. Why did the domain not stop it, and what is the fix?
Show answer
The empty scalar subquery yields a NULL that already has the domain type, so PostgreSQL does not convert it to the domain type again and does not run the domain's NOT NULL check. The fix is to declare the column itself NOT NULL (credit non_negative_money NOT NULL), which is enforced on every write to the table. Existing NULLs must be cleaned up before the constraint can be added.