How to Add a Foreign Key in MySQL
Last updated July 25, 2026 · By the SaturnSQL team
Use ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY ... REFERENCES, and choose an ON DELETE action. The referenced column must be indexed (a primary key is fine) and both column types must match exactly, including UNSIGNED.
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (id)
ON DELETE RESTRICT;ON DELETE options
RESTRICT (the default) blocks deleting a customer that still has orders. CASCADE deletes the orders along with the customer. SET NULL clears customer_id, which then must be nullable.
Error 3780 or errno 150 on ALTER almost always means a type mismatch (e.g. INT vs BIGINT UNSIGNED) or a missing index on the referenced column.
Run this in SaturnSQL
SaturnSQL is a browser-based SQL editor for teams: shared query library, schema-aware autocomplete, and scheduled exports to Google Sheets and Slack.
Try it free