Foreign Keys
A foreign key is a column that references the primary key of another table — the way relational databases enforce relationships.
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
- State the business question Foreign Keys answers and the tables involved.
- Read the workflow diagram and map each stage to parser, optimizer, or storage.
- Write the smallest correct statement (or design change) for a TechLearningPRO Orders/learners dataset.
- Predict the failure mode: wrong cardinality, missing index, or unsafe write — then verify.
Syntax reference
Visual workflow / architecture:
orders.user_id ──FK──▶ users.idInsert order with user_id=999 (no such user)│▼❌ FK violation — INSERT rejectedDELETE 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.
-- TechLearningPRO Orders sketch for: Foreign KeysSELECT id, status, amount_centsFROM ordersWHERE status = 'PENDING'ORDER BY created_at DESCLIMIT 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.
1BeginnerQuestionQ1. What is a foreign key?+
Answer
2IntermediateQuestionQ2. ON DELETE CASCADE vs RESTRICT.+
Answer
3IntermediateQuestionQ3. Should you index a FK column? Why?+
Answer
4AdvancedQuestionQ4. Can a FK reference a UNIQUE column instead of PK?+
Answer
5AdvancedQuestionQ5. Cost of FK enforcement.+
Answer
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.