Bird
Raised Fist0
SQLquery~10 mins

Foreign key linking mental model in SQL - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Foreign key linking mental model
Create Parent Table
Create Child Table with Foreign Key
Insert Data into Parent
Insert Data into Child
Foreign Key Checks: Does Child value exist in Parent?
Yes/No
Allow Insert
Referential Integrity Maintained
This flow shows how a foreign key links a child table to a parent table, ensuring child values exist in the parent to keep data consistent.
Execution Sample
SQL
CREATE TABLE Departments (
  DeptID INT PRIMARY KEY,
  DeptName VARCHAR(50)
);

CREATE TABLE Employees (
  EmpID INT PRIMARY KEY,
  EmpName VARCHAR(50),
  DeptID INT,
  FOREIGN KEY (DeptID) REFERENCES Departments(DeptID)
);
Creates two tables: Departments (parent) and Employees (child) with a foreign key linking Employees.DeptID to Departments.DeptID.
Execution Table
StepActionTableValue InsertedForeign Key CheckResult
1Insert into DepartmentsDepartmentsDeptID=1, DeptName='HR'N/ASuccess
2Insert into DepartmentsDepartmentsDeptID=2, DeptName='Sales'N/ASuccess
3Insert into EmployeesEmployeesEmpID=101, EmpName='Alice', DeptID=1Check DeptID=1 in DepartmentsExists - Success
4Insert into EmployeesEmployeesEmpID=102, EmpName='Bob', DeptID=3Check DeptID=3 in DepartmentsDoes not exist - Fail
5Insert into EmployeesEmployeesEmpID=103, EmpName='Carol', DeptID=2Check DeptID=2 in DepartmentsExists - Success
💡 Step 4 fails because DeptID=3 does not exist in Departments, enforcing foreign key constraint.
Variable Tracker
TableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5
DepartmentsEmpty[{DeptID:1, DeptName:'HR'}][{DeptID:1, DeptName:'HR'}, {DeptID:2, DeptName:'Sales'}][{DeptID:1, DeptName:'HR'}, {DeptID:2, DeptName:'Sales'}][{DeptID:1, DeptName:'HR'}, {DeptID:2, DeptName:'Sales'}][{DeptID:1, DeptName:'HR'}, {DeptID:2, DeptName:'Sales'}]
EmployeesEmptyEmptyEmpty[{EmpID:101, EmpName:'Alice', DeptID:1}][No change - insert failed][{EmpID:101, EmpName:'Alice', DeptID:1}, {EmpID:103, EmpName:'Carol', DeptID:2}]
Key Moments - 2 Insights
Why did the insert fail at step 4 even though the data looks correct?
Because the foreign key DeptID=3 does not exist in the parent Departments table, the database rejects the insert to keep data consistent. See execution_table row 4.
Does the foreign key column in Employees have to be a primary key?
No, the foreign key column in Employees references the primary key in Departments but does not have to be a primary key itself. It just must match existing values in Departments. See concept_flow.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result of inserting EmpID=102 with DeptID=3?
AFail, because DeptID=3 does not exist in Departments
BSuccess, because DeptID=3 is valid
CSuccess, because foreign keys are optional
DFail, because EmpID=102 already exists
💡 Hint
Check execution_table row 4 for foreign key check and result.
At which step does the Employees table first get a new row inserted?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at execution_table rows for Employees insert success.
If we insert a new Department with DeptID=3 before step 4, what would happen at step 4?
AInsert would still fail due to foreign key
BInsert would succeed because DeptID=3 exists
CInsert would fail because DeptID=3 is duplicate
DInsert would succeed but foreign key ignored
💡 Hint
Foreign key checks if referenced DeptID exists in Departments table.
Concept Snapshot
Foreign key links a child table column to a parent table's primary key.
It ensures child values exist in parent to keep data consistent.
Inserts fail if foreign key value not found in parent.
Foreign key column need not be primary key itself.
Used to maintain referential integrity between tables.
Full Transcript
This visual execution shows how foreign keys link two tables in a database. First, a parent table Departments is created with a primary key DeptID. Then a child table Employees is created with a DeptID column referencing Departments.DeptID as a foreign key. When inserting data, Departments accepts new rows freely. Employees can only insert rows if the DeptID value exists in Departments. For example, inserting an employee with DeptID=1 succeeds because Departments has DeptID=1. But inserting with DeptID=3 fails because Departments does not have that value. This enforces referential integrity, preventing orphaned child rows. The variable tracker shows how tables grow after each step. Key moments clarify why inserts fail and foreign key rules. The quiz tests understanding of these steps and constraints. This mental model helps beginners see how foreign keys keep data linked and consistent across tables.

Practice

(1/5)
1. What is the main purpose of a foreign key in a database?
easy
A. To link one table to another and ensure data consistency
B. To store large amounts of text data
C. To speed up database queries
D. To create a backup of the database

Solution

  1. Step 1: Understand the role of foreign keys

    A foreign key connects one table to another by referencing a primary key in the related table.
  2. Step 2: Identify the purpose of this connection

    This connection helps keep data consistent and organized by preventing invalid data entries.
  3. Final Answer:

    To link one table to another and ensure data consistency -> Option A
  4. Quick Check:

    Foreign key = link tables + data consistency [OK]
Hint: Foreign keys link tables to keep data correct [OK]
Common Mistakes:
  • Thinking foreign keys store data themselves
  • Confusing foreign keys with indexes
  • Believing foreign keys speed up queries directly
2. Which of the following is the correct syntax to declare a foreign key in SQL?
easy
A. FOREIGN KEY column_name REFERENCES other_table
B. PRIMARY KEY (column_name) REFERENCES other_table(other_column)
C. FOREIGN KEY (column_name) REFERENCES other_table(other_column)
D. KEY FOREIGN (column_name) REFERENCES other_table(other_column)

Solution

  1. Step 1: Recall the standard foreign key syntax

    The correct syntax includes the keywords FOREIGN KEY, the column in parentheses, then REFERENCES followed by the referenced table and column in parentheses.
  2. Step 2: Compare options to syntax

    FOREIGN KEY (column_name) REFERENCES other_table(other_column) matches the correct syntax exactly. Other options have wrong keyword order or missing parentheses.
  3. Final Answer:

    FOREIGN KEY (column_name) REFERENCES other_table(other_column) -> Option C
  4. Quick Check:

    FOREIGN KEY + REFERENCES + (table.column) = A [OK]
Hint: FOREIGN KEY (col) REFERENCES table(col) is correct syntax [OK]
Common Mistakes:
  • Omitting parentheses around column names
  • Swapping PRIMARY KEY with FOREIGN KEY
  • Incorrect keyword order
3. Given these tables:
CREATE TABLE Authors (AuthorID INT PRIMARY KEY, Name VARCHAR(50));
CREATE TABLE Books (BookID INT PRIMARY KEY, Title VARCHAR(100), AuthorID INT, FOREIGN KEY (AuthorID) REFERENCES Authors(AuthorID));
What happens if you try to insert INSERT INTO Books (BookID, Title, AuthorID) VALUES (1, 'My Book', 99); when there is no author with AuthorID = 99 in Authors?
medium
A. The insert succeeds but AuthorID is set to NULL
B. The insert fails due to foreign key constraint violation
C. The database creates a new author with AuthorID 99 automatically
D. The insert succeeds and adds the book

Solution

  1. Step 1: Understand foreign key constraint behavior

    A foreign key requires that the referenced value exists in the parent table to maintain data integrity.
  2. Step 2: Apply this to the insert statement

    Since AuthorID 99 does not exist in Authors, the insert violates the foreign key constraint and fails.
  3. Final Answer:

    The insert fails due to foreign key constraint violation -> Option B
  4. Quick Check:

    Foreign key requires existing parent row = D [OK]
Hint: Foreign key insert fails if parent key missing [OK]
Common Mistakes:
  • Assuming automatic creation of missing parent rows
  • Thinking insert will succeed with NULL foreign key
  • Ignoring foreign key constraints
4. Consider this table creation:
CREATE TABLE Orders (OrderID INT PRIMARY KEY, CustomerID INT, FOREIGN KEY CustomerID REFERENCES Customers(CustomerID));
What is wrong with this statement?
medium
A. Foreign key cannot reference Customers table
B. CustomerID should be declared as PRIMARY KEY
C. PRIMARY KEY must be declared after FOREIGN KEY
D. Missing parentheses around the foreign key column name

Solution

  1. Step 1: Check foreign key syntax

    The foreign key column name must be enclosed in parentheses after FOREIGN KEY.
  2. Step 2: Identify the error in the statement

    The statement uses FOREIGN KEY CustomerID without parentheses, which is invalid syntax.
  3. Final Answer:

    Missing parentheses around the foreign key column name -> Option D
  4. Quick Check:

    FOREIGN KEY (col) needs parentheses [OK]
Hint: Always use parentheses around foreign key columns [OK]
Common Mistakes:
  • Omitting parentheses in FOREIGN KEY declaration
  • Misordering PRIMARY and FOREIGN KEY declarations
  • Confusing foreign key with primary key requirements
5. You have two tables:
CREATE TABLE Departments (DeptID INT PRIMARY KEY, DeptName VARCHAR(50));
CREATE TABLE Employees (EmpID INT PRIMARY KEY, EmpName VARCHAR(50), DeptID INT, FOREIGN KEY (DeptID) REFERENCES Departments(DeptID) ON DELETE SET NULL);
If a department is deleted, what happens to employees linked to that department?
hard
A. Their DeptID is set to NULL automatically
B. The delete is blocked and fails
C. Employees linked to that department are deleted
D. Nothing happens; DeptID remains unchanged

Solution

  1. Step 1: Understand ON DELETE SET NULL behavior

    This option means when the referenced row is deleted, the foreign key column in dependent rows is set to NULL.
  2. Step 2: Apply to Employees and Departments

    Deleting a department sets DeptID to NULL in Employees who referenced it, keeping employees but removing the link.
  3. Final Answer:

    Their DeptID is set to NULL automatically -> Option A
  4. Quick Check:

    ON DELETE SET NULL means foreign keys become NULL [OK]
Hint: ON DELETE SET NULL clears foreign keys on delete [OK]
Common Mistakes:
  • Assuming delete blocks or cascades employees
  • Thinking employees get deleted automatically
  • Ignoring ON DELETE action effects