Bird
Raised Fist0
SQLquery~10 mins

FOREIGN KEY constraint 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 constraint
Create Parent Table
Create Child Table with FOREIGN KEY
Insert Data into Parent
Insert Data into Child
Check FOREIGN KEY Validity
Allow
This flow shows how a foreign key links child table data to parent table data, allowing inserts only if the referenced parent data exists.
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 as parent and Employees as child with a foreign key linking DeptID.
Execution Table
StepActionTableData InsertedForeign Key CheckResult
1InsertDepartments(1, 'HR')N/ASuccess
2InsertDepartments(2, 'Sales')N/ASuccess
3InsertEmployees(101, 'Alice', 1)DeptID=1 exists in DepartmentsSuccess
4InsertEmployees(102, 'Bob', 3)DeptID=3 does NOT exist in DepartmentsError: Foreign Key Violation
5InsertEmployees(103, 'Carol', 2)DeptID=2 exists in DepartmentsSuccess
💡 Step 4 fails because DeptID=3 is not present in Departments, violating the foreign key constraint.
Variable Tracker
TableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5
Departmentsempty[(1, 'HR')][(1, 'HR'), (2, 'Sales')][(1, 'HR'), (2, 'Sales')][(1, 'HR'), (2, 'Sales')][(1, 'HR'), (2, 'Sales')]
Employeesemptyemptyempty[(101, 'Alice', 1)][(101, 'Alice', 1)] (insert failed)[(101, 'Alice', 1), (103, 'Carol', 2)]
Key Moments - 2 Insights
Why does the insert fail at step 4 even though the Employees table is empty?
Because the foreign key DeptID=3 does not exist in the Departments table, violating the foreign key constraint as shown in execution_table row 4.
Can you insert a row into Employees with a DeptID that is NULL?
Yes, if the foreign key column allows NULLs, because NULL means no reference, so the constraint does not check for a matching parent row.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result of inserting (102, 'Bob', 3) into Employees at step 4?
AIgnored silently
BSuccess
CError: Foreign Key Violation
DInserted with NULL DeptID
💡 Hint
Check the Foreign Key Check and Result columns in execution_table row 4.
At which step does the Employees table first get a successful row inserted?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the Data Inserted and Result columns in execution_table.
If the Departments table had no rows, what would happen when inserting (101, 'Alice', 1) into Employees?
AInsert succeeds
BInsert fails due to foreign key violation
CInsert succeeds but DeptID is set to NULL
DInsert succeeds but with warning
💡 Hint
Refer to the foreign key rule shown in concept_flow and execution_table step 3.
Concept Snapshot
FOREIGN KEY constraint links a child table column to a parent table's primary key.
It ensures child rows reference existing parent rows.
Inserts or updates violating this are rejected.
NULL values are allowed if the foreign key column permits.
Syntax: FOREIGN KEY (child_col) REFERENCES parent_table(parent_col).
Full Transcript
The FOREIGN KEY constraint connects a column in one table (child) to a primary key in another table (parent). This ensures data integrity by allowing only values in the child column that exist in the parent. The flow starts by creating the parent table, then the child table with the foreign key. When inserting data, the database checks if the referenced parent value exists. If yes, the insert succeeds; if not, it fails with an error. For example, inserting an employee with a department ID that does not exist in Departments causes a foreign key violation error. NULL values are allowed if the foreign key column is nullable, meaning no reference is made. This constraint helps keep related data consistent across tables.

Practice

(1/5)
1. What is the main purpose of a FOREIGN KEY constraint in a database?
easy
A. To store large amounts of text data efficiently
B. To speed up database queries by creating indexes
C. To link two tables by ensuring values in one table match values in another
D. To automatically backup the database

Solution

  1. Step 1: Understand the role of FOREIGN KEY

    A FOREIGN KEY connects columns in two tables to keep data related and consistent.
  2. Step 2: Compare options with this role

    Only To link two tables by ensuring values in one table match values in another describes linking tables by matching values, which is the purpose of FOREIGN KEY.
  3. Final Answer:

    To link two tables by ensuring values in one table match values in another -> Option C
  4. Quick Check:

    FOREIGN KEY links tables = A [OK]
Hint: FOREIGN KEY links tables by matching columns [OK]
Common Mistakes:
  • Confusing FOREIGN KEY with indexing
  • Thinking FOREIGN KEY stores data
  • Assuming FOREIGN KEY backs up data
2. Which of the following is the correct syntax to add a FOREIGN KEY constraint to an existing table Orders referencing Customers(CustomerID)?
easy
A. ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID);
B. ALTER TABLE Orders ADD PRIMARY KEY (CustomerID) REFERENCES Customers(CustomerID);
C. ALTER TABLE Orders ADD FOREIGN KEY CustomerID REFERENCES Customers(CustomerID);
D. ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) TO Customers(CustomerID);

Solution

  1. Step 1: Recall correct ALTER TABLE syntax for FOREIGN KEY

    The correct syntax uses: ALTER TABLE table_name ADD FOREIGN KEY (column) REFERENCES other_table(column);
  2. Step 2: Check each option

    ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID); matches the correct syntax exactly. Options A, B, and C have syntax errors or wrong keywords.
  3. Final Answer:

    ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID); -> Option A
  4. Quick Check:

    Correct ALTER TABLE FOREIGN KEY syntax = D [OK]
Hint: Use ADD FOREIGN KEY (col) REFERENCES table(col) syntax [OK]
Common Mistakes:
  • Using PRIMARY KEY instead of FOREIGN KEY
  • Omitting parentheses around column name
  • Using TO instead of REFERENCES keyword
3. Given these tables:
CREATE TABLE Customers (CustomerID INT PRIMARY KEY, Name VARCHAR(50));
CREATE TABLE Orders (OrderID INT PRIMARY KEY, CustomerID INT, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID));
What happens if you try to insert INSERT INTO Orders (OrderID, CustomerID) VALUES (1, 999); when there is no customer with CustomerID = 999?
medium
A. The insert fails due to FOREIGN KEY constraint violation
B. The insert succeeds but CustomerID is set to NULL
C. The insert succeeds and adds the order with CustomerID 999
D. The insert succeeds but triggers a warning

Solution

  1. Step 1: Understand FOREIGN KEY enforcement

    FOREIGN KEY requires the referenced value to exist in the parent table before inserting.
  2. Step 2: Apply to the insert statement

    Since CustomerID 999 does not exist in Customers, the insert violates the FOREIGN KEY rule and fails.
  3. Final Answer:

    The insert fails due to FOREIGN KEY constraint violation -> Option A
  4. Quick Check:

    Insert with missing parent key = fails [OK]
Hint: Insert fails if referenced key doesn't exist [OK]
Common Mistakes:
  • Assuming insert sets foreign key to NULL automatically
  • Thinking insert triggers only warnings, not errors
  • Believing insert succeeds without parent key
4. You have 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. PRIMARY KEY cannot be used with FOREIGN KEY in the same table
B. CustomerID must be declared as PRIMARY KEY
C. REFERENCES keyword is not allowed in FOREIGN KEY constraints
D. FOREIGN KEY must be declared with parentheses around the column name

Solution

  1. Step 1: Check FOREIGN KEY syntax

    FOREIGN KEY columns must be enclosed in parentheses, like FOREIGN KEY (CustomerID).
  2. Step 2: Identify the error in the statement

    The statement misses parentheses around CustomerID in FOREIGN KEY declaration, causing syntax error.
  3. Final Answer:

    FOREIGN KEY must be declared with parentheses around the column name -> Option D
  4. Quick Check:

    FOREIGN KEY columns need parentheses [OK]
Hint: Always use parentheses around FOREIGN KEY columns [OK]
Common Mistakes:
  • Omitting parentheses around foreign key columns
  • Thinking PRIMARY KEY conflicts with FOREIGN KEY
  • Misunderstanding REFERENCES usage
5. You want to delete a customer from Customers table who has orders in Orders table. The Orders table has a FOREIGN KEY on CustomerID referencing Customers(CustomerID) with ON DELETE CASCADE. What will happen when you delete that customer?
hard
A. The delete fails because orders exist for that customer
B. The customer is deleted and all their orders are automatically deleted
C. The customer is deleted but orders remain with invalid CustomerID
D. The delete succeeds but sets CustomerID in orders to NULL

Solution

  1. Step 1: Understand ON DELETE CASCADE effect

    ON DELETE CASCADE means deleting a parent row also deletes all related child rows automatically.
  2. Step 2: Apply to deleting a customer with orders

    Deleting the customer will also delete all orders linked by CustomerID in Orders table.
  3. Final Answer:

    The customer is deleted and all their orders are automatically deleted -> Option B
  4. Quick Check:

    ON DELETE CASCADE deletes related rows [OK]
Hint: ON DELETE CASCADE removes child rows with parent [OK]
Common Mistakes:
  • Assuming delete fails due to existing child rows
  • Thinking child rows remain with broken references
  • Confusing CASCADE with SET NULL behavior