Sub topic 9
Changing domain constraints safely
What you need
This chapter assumes you know how to create a domain with CHECK, NOT NULL, and DEFAULT, and that you know a CHECK that evaluates to NULL passes. It also assumes you can run SQL in psql or a similar client. Everything runs in a scratch schema, so you can clean up at the end.
Why changing a domain is harder than changing a column
A domain is a type, so one rule can govern many columns in many tables. When you change the rule, PostgreSQL must decide what happens to every existing value in all of those columns.
If you add a stricter CHECK the direct way, PostgreSQL scans every table that uses the domain and refuses the change if one row fails. The scan blocks writers for as long as it runs. On a large table that can mean a long outage, or an ALTER that is queued behind a slow transaction while every new writer queues behind it.
NOT VALID and VALIDATE CONSTRAINT split the change into two steps. First the rule starts applying to new writes, which is fast. Later you check the old data on your own schedule.
Setup
This block creates a scratch schema, a domain, and a table with one good row and one row that a future rule will reject.
CREATE SCHEMA domain_lab;
SET search_path = domain_lab;
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,
full_name text,
email email_address NOT NULL
);
INSERT INTO customers (full_name, email) VALUES
('Ada Lovelace', '[email protected]'),
('Long Address', repeat('x', 300) || '@example.com');The second row has a 312-character address. The format rule accepts it, so it was legal when it was inserted. Now suppose the business decides that addresses must be at most 254 characters.
The direct way and why it can hurt
ALTER DOMAIN email_address
ADD CONSTRAINT email_address_max_length
CHECK (length(VALUE) <= 254);This fails, and the domain stays unchanged:
ERROR: column "email" of table "customers" contains values that violate the new constraintThe failure is the good outcome. If every row had passed, you would still have paid for a full scan of every column of this domain type.
Step one: add the constraint as NOT VALID
Add the same rule with NOT VALID:
ALTER DOMAIN email_address
ADD CONSTRAINT email_address_max_length
CHECK (length(VALUE) <= 254) NOT VALID;This succeeds immediately even though row 2 breaks the rule, because PostgreSQL does not look at existing data. The catalog records that the constraint has not been validated:
SELECT conname, convalidated
FROM pg_constraint
WHERE contypid = 'domain_lab.email_address'::regtype
ORDER BY conname; conname | convalidated
----------------------------+--------------
email_address_format | t
email_address_max_length | fconvalidated = false is the marker for work still to do. You can use it to find forgotten half-finished migrations.
What NOT VALID enforces and what it does not
Writes that pass a value through the domain are checked against the new rule. Rows that you do not rewrite are left alone.
-- Rejected: a new long value
INSERT INTO customers (full_name, email)
VALUES ('Too Long', repeat('y', 300) || '@example.com');
-- Accepted: the bad email is not touched
UPDATE customers SET full_name = 'Long Address (reviewed)' WHERE id = 2;
-- Rejected: this assigns a new value to the domain column
UPDATE customers SET email = lower(email) WHERE id = 2;The INSERT fails with:
ERROR: value for domain email_address violates check constraint "email_address_max_length"The last UPDATE fails the same way, because rewriting the column re-checks the value even when it looks the same. Unrelated updates to row 2 keep working, which is what you want during a migration: the application keeps running while you clean up.
The flow looks like this:
Step two: find and fix the offenders
Write the offender query as the opposite of the rule, against the real column. Remember that a CHECK passes when it evaluates to NULL. Use IS FALSE so your query matches exactly what the constraint would reject:
SELECT id, length(email) AS email_length
FROM customers
WHERE (length(email) <= 254) IS FALSE;This returns row 2 with a length of 312. In this example the column is NOT NULL, but the IS FALSE form stays correct when the column allows NULL. A condition such as NOT (length(email) <= 254) also skips NULLs, but it is easy to get wrong with more complex rules.
Deciding what to do with these rows is a business decision. You might ask the customer, truncate, null out the value, or move it to a separate table. This example replaces the value with a placeholder:
UPDATE customers
SET email = 'unknown+' || id || '@example.invalid'
WHERE (length(email) <= 254) IS FALSE;The replacement value is checked against both constraints, and it passes.
Step three: validate
BEGIN;
SET LOCAL lock_timeout = '5s';
ALTER DOMAIN email_address
VALIDATE CONSTRAINT email_address_max_length;
COMMIT;If any row still violates the rule, the statement fails with the same "contains values that violate the new constraint" error and the constraint stays NOT VALID. Fix more rows and run it again. If it succeeds, convalidated becomes true.
SET LOCAL lock_timeout makes the statement give up if it cannot get its lock within 5 seconds. Without it, VALIDATE waits behind any open transaction that touched the table, and new writers queue behind VALIDATE. A timeout turns that stall into an error you can retry. lock_timeout limits waiting for locks only. To cap the scan itself, use statement_timeout.
Validation also has a cost to plan for. For a domain, VALIDATE CONSTRAINT takes a SHARE lock on each table that uses the domain. That blocks INSERT, UPDATE, and DELETE on those tables while the scan runs, though SELECT continues. This is stricter than the table-level ALTER TABLE ... VALIDATE CONSTRAINT, which takes only SHARE UPDATE EXCLUSIVE and lets writes proceed. NOT VALID for domains therefore still saves you time on the ADD, but you cannot assume validation is non-blocking. On a hot table, run it when write traffic is low, and check what it holds with pg_locks on a staging copy first.
| Operation | Scans existing data | Blocks writes to using tables |
|---|---|---|
| `ADD CONSTRAINT ... CHECK` (valid) | Yes | While it scans |
| `ADD CONSTRAINT ... CHECK ... NOT VALID` | No | No scan, so no long lock |
| `VALIDATE CONSTRAINT` | Yes | While it scans |
| `DROP CONSTRAINT` | No | No |
| `RENAME CONSTRAINT` | No | No |
Replacing a constraint
A rule cannot be edited in place. To change it, add a new constraint under a new name and drop the old one. Adding the new one first means there is never a moment with no rule at all.
This example tightens the limit from 254 to 100 characters:
ALTER DOMAIN email_address
ADD CONSTRAINT email_address_max_length_v2
CHECK (length(VALUE) <= 100) NOT VALID;
-- clean up any rows longer than 100 characters, then:
ALTER DOMAIN email_address
VALIDATE CONSTRAINT email_address_max_length_v2;
ALTER DOMAIN email_address
DROP CONSTRAINT email_address_max_length;Both rules apply between the first and last statements. During that window the value must satisfy both, so the stricter rule wins, which is the behavior you want when tightening.
Loosening is simpler in principle, because every existing row already passes the weaker rule. PostgreSQL does not know that, so adding the looser constraint without NOT VALID still scans. You can drop the old constraint and add the new one as NOT VALID in one transaction, and validate later in a quiet period:
BEGIN;
ALTER DOMAIN email_address DROP CONSTRAINT email_address_max_length_v2;
ALTER DOMAIN email_address
ADD CONSTRAINT email_address_max_length_v2
CHECK (length(VALUE) <= 320) NOT VALID;
COMMIT;Leaving a loosened constraint NOT VALID for good works, but it keeps a false in convalidated that will confuse the next person. Validate it once you can afford the lock.
Other ALTER DOMAIN changes
Not every change needs the two-step approach. These commands change defaults and names, and most need no scan:
ALTER DOMAIN email_address RENAME CONSTRAINT email_address_format
TO email_address_has_at_sign;
CREATE DOMAIN priority AS integer DEFAULT 3 NOT NULL
CONSTRAINT priority_range CHECK (VALUE BETWEEN 1 AND 5);
ALTER DOMAIN priority SET DEFAULT 2;
ALTER DOMAIN priority DROP DEFAULT;
ALTER DOMAIN priority DROP NOT NULL;
ALTER DOMAIN priority SET NOT NULL;SET DEFAULTandDROP DEFAULTaffect only future inserts that omit the column. Existing rows are not changed. A default set on the column itself overrides the domain's default.DROP NOT NULLis instant.SET NOT NULLscans every column of the domain type and fails if any contains a NULL. Fix the NULLs before you run it. TheNOT VALIDpattern in this chapter is forCHECKconstraints, which is where it is available in every supported version.DROP CONSTRAINT IF EXISTSis safe to repeat in migration scripts.
Failure modes and gotchas
- Forgotten validation. A migration that adds
NOT VALIDand never validates leaves old rows that break the rule. Later code that assumes the rule holds can be wrong for those rows. Querypg_constraintforconvalidated = falseafter each deploy. - A rewrite re-triggers the check. Updating the domain column itself fails on a bad row even if the new value looks the same as before. An application that rewrites whole rows can hit errors on old rows after you add the constraint.
- NULL passes. A tightened rule such as
length(VALUE) <= 100never rejects NULL. If you also want to forbid NULL, that is a separateNOT NULL, either on the domain or on the column. - Domain
NOT NULLis not airtight. Operations such as outer joins can produce NULL in a value that is nominally of the domain type. UseNOT NULLon the table column for real guarantees. - Rules that read other tables. Do not use subqueries or functions that look at table data in a domain
CHECK. PostgreSQL does not re-check existing values when that other data changes, so the rule drifts out of sync. Use a foreign key for rules that depend on other rows. - Many tables, one lock budget. A domain used in ten tables means ten scans and ten lock acquisitions in one statement. Check
pg_attributefor the columns that use the domain before you run the change.
Cleanup
DROP SCHEMA domain_lab CASCADE;
RESET search_path;Exercise
A table events has 200 million rows and a column code of domain type short_code. You must add CHECK (length(VALUE) = 4) to the domain. Some old rows may violate it, and you cannot block writes for long. Write the sequence of statements, and say what each one costs.
Show answer
First ALTER DOMAIN short_code ADD CONSTRAINT short_code_len CHECK (length(VALUE) = 4) NOT VALID;. It does not scan, so it is quick, and new writes are checked from then on. Next, find old offenders with SELECT ... FROM events WHERE (length(code) = 4) IS FALSE; and fix or remove them. Finally, in a low-traffic period and inside a transaction with SET LOCAL lock_timeout, run ALTER DOMAIN short_code VALIDATE CONSTRAINT short_code_len;. This scans the whole table and blocks writes while it runs, and it fails if any bad row remains, so you fix those rows and retry.
Exercise
After ADD CONSTRAINT ... NOT VALID, a row in customers has an email that breaks the new rule. Which of these succeed: (a) UPDATE customers SET full_name = 'x' WHERE id = 2, (b) UPDATE customers SET email = lower(email) WHERE id = 2, (c) ALTER DOMAIN ... VALIDATE CONSTRAINT? Explain each result.
Show answer
(a) succeeds, because the update does not assign a new value to the domain column, so the bad value is not re-checked. (b) fails, because it assigns a new value to the domain column and that value is checked against the constraint, including the unvalidated one. (c) fails, because validation scans existing rows and finds the one that violates the rule, so the constraint stays NOT VALID.
Exercise
You want to change a domain rule from VALUE <= 100 to VALUE <= 1000 on a numeric domain, with no moment when the domain has no upper bound. What statements do you run?
Show answer
Add the new rule first: ALTER DOMAIN d ADD CONSTRAINT d_max_v2 CHECK (VALUE <= 1000) NOT VALID;. While both rules exist, the stricter old rule still applies, so you cannot yet store values above 100. Then drop the old one with ALTER DOMAIN d DROP CONSTRAINT d_max;. Now only the looser rule applies. Optionally run ALTER DOMAIN d VALIDATE CONSTRAINT d_max_v2; in a quiet period so that convalidated becomes true.