🔗 Foreign Key (`FOREIGN KEY`)

🟢 Beginner

📖 Definition

A Foreign Key is a column (or set of columns) in a child table that points to the Primary Key (or Unique Key) of a parent table. Foreign keys establish relational links between tables and enforce referential integrity, preventing orphaned child records.

🌍 Multilingual Explanations

English

A Foreign Key links child table records to parent table Primary Keys. It guarantees referential integrity, ensuring child rows cannot reference nonexistent parent IDs.

Hindi

Foreign Key do tables ke beech relationship banati hai. Isse child table mein wahi value daal sakte hain jo parent table ki Primary Key mein maujood ho.

Marathi

Foreign Key don tables madhil relation jodne che kaam karte. Parent table chya ID shivay child table madhe invalid value jao shakat nahi.

Hinglish

Foreign Key is a reference link — for example, an orders table has a customer_id foreign key pointing to the customers table's primary key.

🧱 Cascading Referential Actions

When a parent row referenced by a Foreign Key is modified or deleted, SQL engines apply defined referential actions:

Action Behavior on Parent Delete / Update
ON DELETE CASCADE Automatically deletes corresponding child rows when parent row is deleted.
ON DELETE SET NULL Sets foreign key columns in child rows to NULL when parent row is deleted.
ON DELETE RESTRICT / NO ACTION Blocks/rejects parent deletion if child references exist (Default setting).

⚡ SQL Syntax

-- 1. Parent Table
CREATE TABLE departments (
    department_id INT PRIMARY KEY,
    department_name VARCHAR(100) NOT NULL
);

-- 2. Child Table referencing Parent Primary Key
CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    employee_name VARCHAR(100) NOT NULL,
    department_id INT,
    CONSTRAINT fk_emp_dept FOREIGN KEY (department_id)
        REFERENCES departments(department_id)
        ON DELETE SET NULL
        ON UPDATE CASCADE
);

💡 Production Example

-- E-Commerce Orders referencing Customers
CREATE TABLE orders (
    order_id SERIAL PRIMARY KEY,
    order_date DATE NOT NULL,
    customer_id INT NOT NULL,
    total_amount DECIMAL(10, 2),
    CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id)
        REFERENCES customers(customer_id)
        ON DELETE CASCADE
);

-- Inserting parent customer first
INSERT INTO customers (customer_id, first_name, last_name, email)
VALUES (101, 'Rahul', 'Verma', 'rahul@example.com');

-- Inserting child order linked to customer 101
INSERT INTO orders (order_date, customer_id, total_amount)
VALUES ('2026-09-24', 101, 2499.00);

-- Querying with INNER JOIN using Foreign Key relationship
SELECT o.order_id, c.first_name, c.email, o.total_amount
FROM orders o
INNER JOIN customers c ON o.customer_id = c.customer_id;

⚠️ Common Pitfalls & Mistakes

  • Inserting non-existent parent IDs: Attempting to insert a child row with an invalid Foreign Key throws a foreign key constraint violation error (`ERROR 1452: Cannot add or update a child row`).
  • Deleting active parent records: Deleting a parent row without CASCADE fails if child records exist.
  • Forgetting Foreign Key indexes: Unindexed Foreign Key columns slow down `JOIN` queries and table locks during updates.

🎯 Tiered Practice Exercises

  1. Beginner: Create an orders table with a foreign key referencing a customers table.
  2. Intermediate: Demonstrate how ON DELETE CASCADE deletes linked orders when a customer is removed.
  3. Advanced: Write an INNER JOIN query combining three tables linked by foreign keys.

🧭 Navigation

← Previous: Primary Key | Keys Overview | Next: Candidate Key →