Before continuing: This entry is part of the ALTER TABLE guide. If you are new to the topic, start with ALTER TABLE.
Query
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id)
REFERENCES customers (id);
ALTER TABLE orders
ADD CONSTRAINT chk_orders_total
CHECK (total >= 0);Give each constraint an explicit name. That makes the error message easier to recognise, a migration easier to document and the rule easier to remove with DROP CONSTRAINT.
Cases that change the result
SELECT p.id, p.customer_id
FROM orders AS p
LEFT JOIN customers AS c
ON c.id = p.customer_id
WHERE c.id IS NULL;If the first query returns rows, fix or remove those references before adding the foreign key. For a UNIQUEconstraint, group by the candidate column and look for groups with COUNT(*) > 1.
| Check | Result | Interpretation |
|---|---|---|
| Orders with a customer that does not exist | 0 rows | The existing relationship can be validated |
| Repeated non-null emails | 0 groups | No duplicates in the way UNIQUE |
Emails with NULL | 3 rows | The teaching database allows them; exactly how UNIQUE treats multiple NULL depends on the engine |
Watch out for NULL and UNIQUE: PostgreSQL and MySQL usually allow several null values in a unique key; SQL Server treats NULL as repeated values in a regular unique index or constraint UNIQUE and allows only one. If in SQL Server you need “unique emails where present” alongside several unknown emails, use a filtered unique index on email IS NOT NULL. Do not carry a nullability strategy from one engine to another without checking it.
An empty result is a checkpoint, not an absolute guarantee: avoid concurrent writes during the migration or use whatever safe deployment mechanism your engine provides.
Avoid this confusion
Adding the rule before cleaning the data
A migration can stop halfway through because of duplicates, null values or orphaned references. Run diagnostic queries, measure how many rows need fixing and prepare a rollback.
Do not confuse the constraint with the index. Some engines create or require indexes for certain keys, but dropping an index does not always remove the constraint, and vice versa.