A FOREIGN KEY constraint links two tables together. It makes sure that the data in one table matches data in another table, keeping information correct and connected.
FOREIGN KEY constraint in SQL
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
SQL
CREATE TABLE ChildTable ( column1 datatype, column2 datatype, ..., FOREIGN KEY (column_name) REFERENCES ParentTable(parent_column) );
The FOREIGN KEY column in the child table must match the data type of the referenced column in the parent table.
The referenced column in the parent table is usually a PRIMARY KEY or UNIQUE.
Examples
SQL
CREATE TABLE Orders ( OrderID int PRIMARY KEY, CustomerID int, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) );
SQL
CREATE TABLE Enrollment ( StudentID int, CourseID int, FOREIGN KEY (StudentID) REFERENCES Students(StudentID), FOREIGN KEY (CourseID) REFERENCES Courses(CourseID) );
Sample Program
This example creates two tables: Departments and Employees. Employees have a DeptID that must exist in Departments. Then it inserts data and shows employee names with their department names.
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) ); INSERT INTO Departments VALUES (1, 'Sales'); INSERT INTO Departments VALUES (2, 'HR'); INSERT INTO Employees VALUES (101, 'Alice', 1); INSERT INTO Employees VALUES (102, 'Bob', 2); SELECT EmpName, DeptName FROM Employees JOIN Departments ON Employees.DeptID = Departments.DeptID;
Important Notes
If you try to insert a value in the child table that does not exist in the parent table, the database will give an error.
Deleting a row in the parent table that is referenced by the child table can be blocked or cause changes depending on the FOREIGN KEY settings.
Summary
FOREIGN KEY connects two tables by matching columns.
It helps keep data accurate and related.
Use it to enforce rules about what data can be entered or deleted.
Practice
1. What is the main purpose of a
FOREIGN KEY constraint in a database?easy
Solution
Step 1: Understand the role of FOREIGN KEY
A FOREIGN KEY connects columns in two tables to keep data related and consistent.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.Final Answer:
To link two tables by ensuring values in one table match values in another -> Option CQuick 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
Solution
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);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.Final Answer:
ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID); -> Option AQuick 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:
What happens if you try to insert
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
Solution
Step 1: Understand FOREIGN KEY enforcement
FOREIGN KEY requires the referenced value to exist in the parent table before inserting.Step 2: Apply to the insert statement
Since CustomerID 999 does not exist in Customers, the insert violates the FOREIGN KEY rule and fails.Final Answer:
The insert fails due to FOREIGN KEY constraint violation -> Option AQuick 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:
What is wrong with this statement?
CREATE TABLE Orders (OrderID INT PRIMARY KEY, CustomerID INT, FOREIGN KEY CustomerID REFERENCES Customers(CustomerID));What is wrong with this statement?
medium
Solution
Step 1: Check FOREIGN KEY syntax
FOREIGN KEY columns must be enclosed in parentheses, like FOREIGN KEY (CustomerID).Step 2: Identify the error in the statement
The statement misses parentheses around CustomerID in FOREIGN KEY declaration, causing syntax error.Final Answer:
FOREIGN KEY must be declared with parentheses around the column name -> Option DQuick 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
Solution
Step 1: Understand ON DELETE CASCADE effect
ON DELETE CASCADE means deleting a parent row also deletes all related child rows automatically.Step 2: Apply to deleting a customer with orders
Deleting the customer will also delete all orders linked by CustomerID in Orders table.Final Answer:
The customer is deleted and all their orders are automatically deleted -> Option BQuick 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
