SQL Tutorial 0/85 lessons ~6 min read Lesson 18

    Foreign Keys

    A foreign key is a column that references the primary key of another table — the way relational databases enforce relationships.

    Course progress0%
    Focus
    13 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    A foreign key is a column that references the primary key of another table — the way relational databases enforce relationships. Without FKs, your data integrity lives entirely in app code (and breaks).

    Learning objective: Apply Foreign Keys correctly in a TechLearningPRO production database — with clear query intent, safe defaults, and failure modes you can explain in review.

    Treat every example as production-shaped SQL: explicit column lists, deterministic predicates, and indexes that match the access path. Prefer PostgreSQL dialect notes when dialects diverge; call out MySQL differences when they matter.

    Purpose of this lesson

    Apply Foreign Keys correctly in a TechLearningPRO production database — with clear query intent, safe defaults, and failure modes you can explain in review.

    Understanding the topic

    Core concepts to understand:

    • FOREIGN KEY (user_id) REFERENCES users(id).
    • DB rejects inserts/updates that point to nonexistent rows.
    • ON DELETE CASCADE deletes children automatically.
    • ON DELETE RESTRICT/NO ACTION blocks delete if children exist.
    • ON DELETE SET NULL nulls the FK.

    Step-by-step explanation

    1. State the business question Foreign Keys answers and the tables involved.
    2. Read the workflow diagram and map each stage to parser, optimizer, or storage.
    3. Write the smallest correct statement (or design change) for a TechLearningPRO Orders/learners dataset.
    4. Predict the failure mode: wrong cardinality, missing index, or unsafe write — then verify.

    Syntax reference

    Visual workflow / architecture:

    bash
    orders.user_id ──FK──▶ users.id
    Insert order with user_id=999 (no such user)
    │
    ▼
    ❌ FK violation — INSERT rejected
    DELETE user 5
    └ ON DELETE CASCADE → all orders of user 5 deleted
    └ ON DELETE RESTRICT → blocked
    └ ON DELETE SET NULL → orders.user_id = NULL

    Informative example

    Shape to practice: rewrite the diagram as an explicit SQL statement against orders(id, learner_id, status, amount_cents, created_at) — select only the columns you need.

    sql
    -- TechLearningPRO Orders sketch for: Foreign Keys
    SELECT id, status, amount_cents
    FROM orders
    WHERE status = 'PENDING'
    ORDER BY created_at DESC
    LIMIT 50;

    Real-world use

    Banks, ledgers, and any system tracking money use foreign keys + transactions to guarantee that a payment can never reference a missing account.

    Security implications

    SQL is a trust boundary. Application code must never concatenate untrusted input into statements.

    • Use bind parameters / prepared statements — never string-built SQL from request bodies.
    • Least-privilege DB roles: app users should not own DDL in production.
    • Avoid returning raw DB errors to clients; log server-side with a correlation id.

    Best practices

    • Always declare FKs — let the DB enforce integrity.
    • Index every FK column — joins and CASCADE deletes need it.
    • Pick CASCADE/RESTRICT consciously per relationship.

    Common mistakes

    • Skipping FKs 'for performance' → silent corruption later.
    • Forgetting to index the FK column → slow joins.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    5 questions
    1BeginnerQuestionQ1. What is a foreign key?+

    Answer

    FKs enforce relationships at the DB layer.
    2IntermediateQuestionQ2. ON DELETE CASCADE vs RESTRICT.+

    Answer

    Always index FK columns.
    3IntermediateQuestionQ3. Should you index a FK column? Why?+

    Answer

    ON DELETE behaviors are crucial design choices.
    4AdvancedQuestionQ4. Can a FK reference a UNIQUE column instead of PK?+

    Answer

    ON DELETE behaviors are crucial design choices.
    5AdvancedQuestionQ5. Cost of FK enforcement.+

    Answer

    ON DELETE behaviors are crucial design choices.

    Hands-on exercise

    Hands-on + interview drill:

    • Implement the smallest correct example for Foreign Keys on an Orders-like schema.
    • Q1. What is a foreign key?
    • Q2. ON DELETE CASCADE vs RESTRICT.
    • Q3. Should you index a FK column? Why?
    • Q4. Can a FK reference a UNIQUE column instead of PK?
    • Q5. Cost of FK enforcement.

    Summary

    Foreign Keys is a production SQL skill: state the question, write the precise statement, and prove it with an execution plan or constraint — not with lucky result sets.

    Ready to mark this lesson complete?Track your journey across the entire course.