Sub topic 16
Adding and dropping constraints on existing tables
This chapter assumes you can write CREATE TABLE with primary and foreign keys, read ALTER TABLE syntax, and run a LEFT JOIN. Examples use PostgreSQL. Other systems are covered near the end.
Real schemas rarely come out right the first time. A table is imported without keys, or a foreign key is forgotten, or a delete rule turns out to be wrong. You then change the constraint on a table that already holds data. That data is the hard part: the database checks every existing row against the new rule.
Naming constraints
Every constraint has a name, whether you choose one or not. If you leave it out, PostgreSQL generates one. Generated names follow patterns such as customers_pkey and orders_customer_id_fkey. Other systems generate different names, some of them opaque. A constraint you need to drop later is easier to handle when you named it yourself.
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (customer_id);To find the names of the constraints on a table, query the system catalog:
SELECT conname, contype
FROM pg_constraint
WHERE conrelid = 'orders'::regclass;In contype, p is a primary key, f is a foreign key, u is unique, and c is a check constraint. In psql, the command \d orders shows the same information.
Adding a primary key to an existing table
A primary key requires every value to be unique and non-null. The command fails if the existing data breaks either rule. Check first:
CREATE TABLE products_import (
sku VARCHAR(20),
name VARCHAR(100)
);
-- Duplicate values that would block the key
SELECT sku, COUNT(*) AS copies
FROM products_import
GROUP BY sku
HAVING COUNT(*) > 1;
-- NULLs that would block the key
SELECT * FROM products_import WHERE sku IS NULL;
ALTER TABLE products_import
ADD CONSTRAINT pk_products_import PRIMARY KEY (sku);PostgreSQL marks the key column NOT NULL for you as part of this command. It also builds a unique index to enforce the key, so on a large table the command takes time and holds a lock. A table can have only one primary key. If one exists, drop it first or use a UNIQUE constraint instead.
Adding a foreign key to existing data
When you add a foreign key, the database checks every child row. One orphan, meaning a child row whose parent does not exist, makes the whole statement fail. Find the orphans yourself first:
SELECT o.order_id, o.customer_id
FROM orders AS o
LEFT JOIN customers AS c ON c.customer_id = o.customer_id
WHERE o.customer_id IS NOT NULL
AND c.customer_id IS NULL;The IS NOT NULL test matters. A NULL foreign key is allowed and is not an orphan (see the chapter on optional relationships). For each orphan row, you can do one of these:
- Create the missing parent.
- Point the row at the correct parent.
- Set the foreign key to
NULLif the column allows it. - Delete the row.
Pick the one that matches what the data means. Do not delete rows only to make the constraint pass.
Adding a foreign key without a long lock (PostgreSQL)
A plain ADD CONSTRAINT ... FOREIGN KEY scans the whole child table while it holds a lock that blocks writes. On a big table that can stall an application. PostgreSQL lets you split the work into two steps:
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
NOT VALID;
ALTER TABLE orders
VALIDATE CONSTRAINT fk_orders_customer;NOT VALID skips the check of old rows but enforces the rule for every new insert and update right away. VALIDATE CONSTRAINT then checks the old rows while taking a weaker lock, so normal reads and writes continue. If old rows turn out to be orphans, validation fails and the constraint stays in the not-valid state until you repair the data and run it again.
Dropping constraints
Drop a constraint by name:
ALTER TABLE orders DROP CONSTRAINT fk_orders_customer;Dropping a foreign key only removes the rule. The data stays as it is, and the column keeps its values. Dropping a primary key that other tables reference is blocked, because those foreign keys depend on it:
-- Fails if orders.customer_id still references customers
ALTER TABLE customers DROP CONSTRAINT customers_pkey;
-- Drops the primary key and every foreign key that depends on it
ALTER TABLE customers DROP CONSTRAINT customers_pkey CASCADE;CASCADE here removes constraints, not rows. Still, it silently removes the integrity rules on other tables, so list the dependent constraints first and re-create them afterward.
Changing an existing constraint
You cannot edit a foreign key's ON DELETE or ON UPDATE action in place. You drop the constraint and add it again. Do both steps in one transaction so no other session can insert bad rows between them. PostgreSQL supports transactional DDL (schema-changing statements), so this is safe:
BEGIN;
ALTER TABLE orders DROP CONSTRAINT fk_orders_customer;
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
ON DELETE RESTRICT
ON UPDATE CASCADE;
COMMIT;Re-adding the constraint checks every row again, so the cost is the same as adding it for the first time. In MySQL, DDL statements commit implicitly and cannot be rolled back, so there is a short window with no constraint. Plan for it.
Differences between systems
| System | Drop a foreign key | Add without checking old rows |
|---|---|---|
| PostgreSQL | `DROP CONSTRAINT name` | `NOT VALID`, then `VALIDATE CONSTRAINT` |
| MySQL | `DROP FOREIGN KEY name` | Set `foreign_key_checks = 0` for the session (risky) |
| SQL Server | `DROP CONSTRAINT name` | `WITH NOCHECK`, then `WITH CHECK CHECK CONSTRAINT name` |
| Oracle | `DROP CONSTRAINT name` | `ENABLE NOVALIDATE`, then `MODIFY CONSTRAINT name VALIDATE` |
MySQL also uses DROP PRIMARY KEY, with no name, because a table has only one.
Common mistakes
- Adding a foreign key without checking for orphans first, then debugging the error message with no list of bad rows.
- Relying on generated constraint names in migration scripts. Names can differ between environments, so the script breaks. Name constraints in your scripts.
- Dropping a primary key with
CASCADEand forgetting that the foreign keys are gone. - Changing a delete rule outside a transaction and leaving a gap with no protection.
- Adding the foreign key but not an index on the child column. Constraint changes do not create one in PostgreSQL.
Exercise
The table shipments(shipment_id, order_id) already holds data and has no foreign key. You want order_id to reference orders(order_id) on a table that serves live traffic, and you suspect a few orphan rows. Write the sequence of steps and statements you would use in PostgreSQL.
Show answer
First find orphans: SELECT s.shipmentid FROM shipments AS s LEFT JOIN orders AS o ON o.orderid = s.orderid WHERE s.orderid IS NOT NULL AND o.orderid IS NULL; Repair them (create the parent, repoint the row, set NULL, or delete). Then run ALTER TABLE shipments ADD CONSTRAINT fkshipmentsorder FOREIGN KEY (orderid) REFERENCES orders (orderid) NOT VALID; so new writes are checked immediately without a long lock, followed by ALTER TABLE shipments VALIDATE CONSTRAINT fkshipmentsorder; to check the old rows. Finally add CREATE INDEX idxshipmentsorderid ON shipments (order_id); because PostgreSQL does not index foreign key columns automatically.