Sub topic 9
Changing Domain Constraints Safely
This chapter assumes that you know basic PostgreSQL SQL, including CREATE TABLE, ALTER TABLE, CHECK, NOT NULL, and domains. You should also understand that a domain is a reusable type with rules that apply wherever the domain is used.
A domain constraint can affect many tables. Before changing one, find every column that uses the domain and decide how existing values should be handled.
Why domain changes need a rollout plan
Suppose a domain currently checks only the general shape of an email address:
CREATE DOMAIN customer_email AS text
CONSTRAINT customer_email_format
CHECK (VALUE ~* '^[^@[:space:]]+@[^@[:space:]]+$');
CREATE TABLE domain_customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email customer_email NOT NULL
);Later, you want to require that an email address has at most 254 characters. Existing rows might violate this new rule. Adding a normal constraint would need to check those rows immediately, which can fail or create a long migration.
PostgreSQL supports a staged approach:
- Add the new
CHECKconstraint withNOT VALID. - Keep enforcing the constraint for new or changed values.
- Find and fix existing invalid values.
- Run
VALIDATE CONSTRAINTto check the remaining rows.
NOT VALID does not mean that the rule is ignored. It means that PostgreSQL does not scan existing values when the constraint is added.
Find columns that use a domain
A domain constraint is shared. If five tables use the same domain, changing the domain changes the rule for all five tables.
This catalog query finds direct table columns using the customer_email domain in the public schema:
SELECT
n.nspname AS table_schema,
c.relname AS table_name,
a.attname AS column_name
FROM pg_catalog.pg_attribute AS a
JOIN pg_catalog.pg_class AS c
ON c.oid = a.attrelid
JOIN pg_catalog.pg_namespace AS n
ON n.oid = c.relnamespace
JOIN pg_catalog.pg_type AS domain_type
ON domain_type.oid = a.atttypid
WHERE domain_type.typname = 'customer_email'
AND domain_type.typnamespace = 'public'::regnamespace
AND a.attnum > 0
AND NOT a.attisdropped
AND c.relkind IN ('r', 'p');Also inspect the existing data in every returned column. A constraint expression that is easy to check in one table may need a different query in another table.
Add a constraint with `NOT VALID`
The following example creates an existing value that is valid under the old rule but too long for the new rule:
INSERT INTO domain_customers (email)
VALUES
('[email protected]'),
(repeat('x', 250) || '@example.com');
ALTER DOMAIN customer_email
ADD CONSTRAINT customer_email_max_length
CHECK (length(VALUE) <= 254) NOT VALID;The new constraint is now attached to the domain. PostgreSQL does not yet know whether all existing values satisfy it.
A new invalid value is rejected immediately:
-- This statement would fail because new values are checked.
-- INSERT INTO domain_customers (email)
-- VALUES (repeat('y', 250) || '@example.com');Updates to existing rows are also checked because an update assigns a value to the domain column. This prevents an application from modifying an old row and preserving or introducing a value that violates the new rule.
Fix existing values and validate
Use application-specific rules to repair old data. Do not silently truncate values unless truncation is correct for the data.
SELECT id, email
FROM domain_customers
WHERE length(email) > 254;
UPDATE domain_customers
SET email = '[email protected]'
WHERE id = 2;
ALTER DOMAIN customer_email
VALIDATE CONSTRAINT customer_email_max_length;VALIDATE CONSTRAINT scans the existing values in columns that use the domain. If any value violates the constraint, validation fails and the constraint remains unvalidated. Fix the remaining rows and run validation again.
After successful validation, PostgreSQL treats the constraint as verified for existing data as well as enforced for future changes.
Plan for locks and failures
Validation can scan substantial amounts of data and can take locks while PostgreSQL checks the affected columns. Test the operation on production-sized data and run it during a suitable maintenance period if necessary.
A useful migration sequence separates schema preparation from data repair:
- Add the constraint with
NOT VALID. - Deploy or enable code that writes only valid values.
- Repair existing invalid rows in batches if the tables are large.
- Validate the constraint.
- Monitor for application errors during the rollout.
Only CHECK constraints support the NOT VALID form for domains. A domain's DEFAULT and NOT NULL properties do not use this staged validation syntax. For example, ALTER DOMAIN ... SET NOT NULL requires the existing domain values to satisfy the non-null requirement.
If the new rule is wrong, remove it explicitly:
ALTER DOMAIN customer_email
DROP CONSTRAINT customer_email_max_length;Dropping the constraint immediately permits values that violate that rule, so coordinate the change with application validation and database migrations.
> callout note > A domain constraint is global to the domain, not local to one table. Validate every table that uses the domain before declaring the migration complete.
Exercise
Exercise
A domain named postal_code allows text values, and existing rows include NULL and values of different lengths. You need to require exactly five characters while allowing NULL. What staged migration should you use?
Show answer
Add CHECK (length(VALUE) = 5) NOT VALID, repair existing non-NULL values that are not five characters, and run ALTER DOMAIN postal_code VALIDATE CONSTRAINT constraint_name. The check allows NULL because a CHECK that evaluates to NULL passes.