Sub topic 8
Adding and dropping constraints
This chapter assumes you can write CREATE TABLE, know what primary and foreign keys are, and have read the earlier chapters on ALTER TABLE structure and columns. The examples use PostgreSQL syntax. Dialect differences are collected in a table near the end.
Why change constraints after the fact
A constraint is a rule the database enforces on every write. You usually declare constraints in CREATE TABLE, but real schemas change. A business rule appears, a bug lets bad data in, or a table was created without a rule it should have had. ALTER TABLE lets you add or remove a rule without rebuilding the table.
The constraints you can manage this way are:
PRIMARY KEYUNIQUECHECKFOREIGN KEYNOT NULLandDEFAULT. Most systems treat these as column properties changed withALTER COLUMN, not as named constraints.
Starting tables
The examples below build on these two tables.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255),
status VARCHAR(20) NOT NULL DEFAULT 'active'
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
total NUMERIC(10, 2) NOT NULL
);Adding constraints
The general form is ALTER TABLE table ADD CONSTRAINT name definition. Always supply the name. If you omit it, the database invents one, such as orders_total_check in PostgreSQL. Generated names differ between systems and are awkward to type in a later DROP.
ALTER TABLE customers
ADD CONSTRAINT uq_customers_email UNIQUE (email);
ALTER TABLE customers
ADD CONSTRAINT ck_customers_status
CHECK (status IN ('active', 'suspended', 'closed'));
ALTER TABLE orders
ADD CONSTRAINT ck_orders_total CHECK (total >= 0);
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (id);A consistent naming scheme helps. This chapter uses pk_, uq_, ck_ and fk_ prefixes followed by the table and column or purpose.
Existing rows must already comply
When you add a constraint, the database first checks the rows already in the table. If any row breaks the rule, the statement fails and the table is left unchanged. The constraint is never added in a half-applied state.
So the usual workflow is to look for violations first. Each query below returns the rows that would block the matching constraint.
-- Would block uq_customers_email: duplicated non-null emails
SELECT email, COUNT(*) AS copies
FROM customers
WHERE email IS NOT NULL
GROUP BY email
HAVING COUNT(*) > 1;
-- Would block fk_orders_customer: orders pointing at missing customers
SELECT o.id, o.customer_id
FROM orders AS o
LEFT JOIN customers AS c ON c.id = o.customer_id
WHERE c.id IS NULL;
-- Would block ck_orders_total: negative totals
SELECT id, total FROM orders WHERE total < 0;Fix or delete those rows, then add the constraint.
NULL and CHECK
A CHECK constraint rejects a row only when the condition evaluates to false. If it evaluates to unknown, which happens when a NULL is involved, the row passes. For example, CHECK (total >= 0) accepts a NULL total. Combine it with NOT NULL when you want both rules. Similarly, a UNIQUE constraint in PostgreSQL and MySQL allows many NULL values. SQL Server allows only one.
Dropping constraints
Dropping needs the constraint name. In PostgreSQL the syntax is the same for every constraint type.
ALTER TABLE orders DROP CONSTRAINT ck_orders_total;
ALTER TABLE orders DROP CONSTRAINT fk_orders_customer;
ALTER TABLE customers DROP CONSTRAINT IF EXISTS uq_customers_email;IF EXISTS is the same re-runnable guard used with DROP TABLE. It turns a missing constraint into a notice instead of an error.
If you don't remember the name, ask the catalog. In PostgreSQL:
SELECT conname, contype, pg_get_constraintdef(oid) AS definition
FROM pg_constraint
WHERE conrelid = 'orders'::regclass;The contype letters are p for primary key, u for unique, c for check and f for foreign key. The portable alternative is information_schema.table_constraints.
Dropping a constraint is cheap and loses no data. The rows stay as they are. What you lose is the guarantee. Once the rule is gone, bad rows can enter, and re-adding the rule later may fail.
Dependencies block some drops
A primary key or unique constraint can be the target of a foreign key. PostgreSQL refuses to drop it while a foreign key still depends on it.
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (id);
-- Fails: constraint fk_orders_customer depends on customers_pkey
ALTER TABLE customers DROP CONSTRAINT customers_pkey;
-- Succeeds, and also drops fk_orders_customer
ALTER TABLE customers DROP CONSTRAINT customers_pkey CASCADE;CASCADE removes the dependent foreign key but not the orders table or any of its rows. Prefer dropping the foreign key yourself first, so the sequence is explicit in your migration. The default behavior is RESTRICT, which is the refusal shown above.
Large tables: add now, validate later
Adding a CHECK or foreign key makes the database scan the whole table, and it holds a lock while it does so. On a table with hundreds of millions of rows that can stall writes for a long time. PostgreSQL lets you split the work into two steps.
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (id)
NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT fk_orders_customer;The first statement enforces the rule for new and changed rows immediately, but skips the scan of old rows. The second statement does the scan under a weaker lock that lets normal reads and writes continue. If old rows are bad, only the VALIDATE step fails, and the constraint stays in place for new data while you clean up. NOT VALID applies to CHECK and foreign key constraints, not to UNIQUE or PRIMARY KEY.
Dialect differences
| Task | PostgreSQL | MySQL 8 | SQL Server | SQLite |
|---|---|---|---|---|
| Add a named constraint | `ADD CONSTRAINT` | `ADD CONSTRAINT` | `ADD CONSTRAINT` | Not supported |
| Drop a foreign key | `DROP CONSTRAINT name` | `DROP FOREIGN KEY name` (`DROP CONSTRAINT` from 8.0.19) | `DROP CONSTRAINT name` | Not supported |
| Drop a unique constraint | `DROP CONSTRAINT name` | `DROP INDEX name` (`DROP CONSTRAINT` from 8.0.19) | `DROP CONSTRAINT name` | Not supported |
| Drop a check constraint | `DROP CONSTRAINT name` | `DROP CHECK name` (`DROP CONSTRAINT` from 8.0.19) | `DROP CONSTRAINT name` | Not supported |
| Drop a primary key | `DROP CONSTRAINT table_pkey` | `DROP PRIMARY KEY` | `DROP CONSTRAINT name` | Not supported |
SQLite cannot add or drop most constraints with ALTER TABLE. The usual approach is to create a new table with the desired constraints, copy the rows across with INSERT ... SELECT, drop the old table and rename the new one. MySQL enforces CHECK constraints only from version 8.0.16. Earlier versions parse and silently ignore them.
Transactions and safety
In PostgreSQL, constraint changes are transactional. You can wrap several in BEGIN and COMMIT, and a failure rolls them all back. MySQL commits implicitly after each DDL statement, so a half-finished sequence stays half-finished. Before dropping a constraint in production, record its definition (from the catalog query above) so you can restore it with the matching ADD CONSTRAINT.
Exercise
You run ALTER TABLE orders ADD CONSTRAINT ck_orders_total CHECK (total >= 0) on a 200-million-row PostgreSQL table, and you can't afford a long scan under a heavy lock. What two statements would you run instead, and what does each do?
Show answer
First ALTER TABLE orders ADD CONSTRAINT ck_orders_total CHECK (total >= 0) NOT VALID;, which enforces the rule for new and updated rows without scanning existing rows. Then ALTER TABLE orders VALIDATE CONSTRAINT ck_orders_total;, which scans the existing rows under a lock that still permits normal reads and writes. If old rows violate the rule, only the second statement fails.
Exercise
In PostgreSQL, ALTER TABLE customers DROP CONSTRAINT customers_pkey; fails while orders has a foreign key to customers (id). Give two ways to make the drop succeed, and say which you would prefer in a migration script.
Show answer
Run ALTER TABLE orders DROP CONSTRAINT fk_orders_customer; first and then drop the primary key. Or add CASCADE to the primary key drop, which also removes the dependent foreign key. The first is preferable, because the migration then states every change explicitly and does not silently remove other objects.