Useful Data Tips

Foreign Keys and Referential Integrity

⏱️ 29 sec read 📊 SQL

Foreign keys enforce relationships between tables, ensuring data consistency. They prevent orphaned records and maintain referential integrity across your database.

Creating a Foreign Key

CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT NOT NULL,
    order_date DATE,
    total DECIMAL(10,2),
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

Adding Foreign Key to Existing Table

ALTER TABLE order_items
ADD CONSTRAINT fk_order
FOREIGN KEY (order_id) REFERENCES orders(order_id);

Cascade Operations

CASCADE DELETE

-- When customer is deleted, all their orders are deleted too
CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
        ON DELETE CASCADE
);

CASCADE UPDATE

-- When customer_id changes, update all related orders
CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
        ON UPDATE CASCADE
);

SET NULL Option

-- When department is deleted, set employee's dept_id to NULL
CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    dept_id INT,
    FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
        ON DELETE SET NULL
);

Common Cascade Options

Pro Tip: Always use foreign keys to enforce data integrity at the database level. Use CASCADE carefully—it's powerful but can accidentally delete large amounts of data. Test thoroughly!

← Back to SQL Tips