</>
Skip to content
MySQL lessons (36/48)

MySQL — Foreign Key

Basic Foreign Key

CREATE TABLE orders (
    id INT PRIMARY KEY,
    customer_id INT,
    total DECIMAL(10,2),
    FOREIGN KEY (customer_id) REFERENCES customers(id)
);

Named Foreign Key

CREATE TABLE orders (
    id INT PRIMARY KEY,
    customer_id INT,
    CONSTRAINT fk_customer FOREIGN KEY (customer_id)
        REFERENCES customers(id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

ON DELETE Actions

ActionBehavior
CASCADEDelete child rows when parent is deleted
SET NULLSet foreign key to NULL
SET DEFAULTSet to default value
NO ACTIONPrevent deletion (default)
RESTRICTPrevent deletion (same as NO ACTION)

ON UPDATE Actions

FOREIGN KEY (customer_id) REFERENCES customers(id)
    ON UPDATE CASCADE

Adding Foreign Key After Creation

ALTER TABLE orders
ADD CONSTRAINT fk_customer
FOREIGN KEY (customer_id) REFERENCES customers(id);

Dropping Foreign Key

ALTER TABLE orders DROP FOREIGN KEY fk_customer;

Viewing Foreign Keys

SELECT * FROM information_schema.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_NAME = 'customers';

Mini Practice

Write SQL code that:

  1. Creates two related tables with a foreign key
  2. Uses ON DELETE CASCADE
  3. Uses ON DELETE SET NULL
  4. Adds a foreign key to an existing table

Up Next

Continue with Unique — ensuring no duplicate values.

Related Topics

Frequently Asked Questions about Foreign Key

What is Foreign Key in MySQL?

Foreign Key is a fundamental concept in MySQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Foreign Key?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Foreign Key.

Why is Foreign Key important in MySQL?

Foreign Key is essential for MySQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.