Lesson

MySQL FOREIGN KEY

10 min reading
Free Course

MySQL FOREIGN KEY: Linking Tables With Referential Integrity

A MySQL FOREIGN KEY links a column in a child table to a PRIMARY KEY (or indexed UNIQUE key) in a parent table. It enforces referential integrity by blocking orphan child rows that point to nonexistent parent IDs.

Referential Actions (ON DELETE and ON UPDATE)

  • RESTRICT / NO ACTION (Default): Blocks deleting or changing a parent ID while child rows still reference it.
  • CASCADE: Automatically deletes (or updates) matching child rows when the parent row changes.
  • SET NULL: Sets the child foreign key column to NULL when the parent row is deleted (requires the child column to be nullable).

Practical SQL Example

This schema ties demo_orders.customer_id to demo_customers.id so no order can reference a missing customer:

CREATE TABLE demo_orders (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    customer_id BIGINT UNSIGNED NOT NULL,
    total_amount DECIMAL(10, 2) NOT NULL,
    CONSTRAINT fk_demo_orders_customer
        FOREIGN KEY (customer_id)
        REFERENCES demo_customers(id)
        ON DELETE RESTRICT
        ON UPDATE CASCADE
) ENGINE=InnoDB;

Common Mistakes and Best Practices

  • Match Column Types and Signedness Exactly: If demo_customers.id is BIGINT UNSIGNED, then demo_orders.customer_id must also be BIGINT UNSIGNED—not INT or signed BIGINT. Type mismatches cause MySQL's infamous errno 150 (Foreign key constraint is incorrectly formed).
  • Use ON DELETE CASCADE Carefully: Cascading deletes on demo_customers -> demo_orders -> demo_order_items can wipe out financial history silently; prefer RESTRICT plus soft deletes on business records.
  • Name Constraints Clearly: Naming fk_demo_orders_customer makes ALTER TABLE demo_orders DROP FOREIGN KEY fk_demo_orders_customer; simple later.

Frequently Asked Questions

Do foreign keys require an index on the child column?

Yes, MySQL automatically creates an index on the child foreign key column if one does not already exist so parent deletes check child rows fast.

Can a foreign key column allow NULL?

Yes, when the relationship is optional (like manager_id on top executives), NULL is allowed and skips the parent lookup.

Why did FOREIGN KEY creation fail with errno 150?

Almost always because the parent table is missing, the referenced column isn't indexed, or the two columns differ in integer size, signedness, or string collation.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum