FOREIGN KEY constraint in SQL - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we use a FOREIGN KEY constraint, the database checks that related data exists. This checking takes time.
We want to understand how this checking time grows as the data grows.
Analyze the time complexity of inserting a row with a FOREIGN KEY constraint.
INSERT INTO Orders (OrderID, CustomerID, OrderDate)
VALUES (101, 5, '2024-06-01');
-- CustomerID is a FOREIGN KEY referencing Customers(CustomerID)
This code inserts a new order and checks if the CustomerID exists in the Customers table.
When inserting, the database must check the FOREIGN KEY value exists.
- Primary operation: Searching the referenced table for the matching key.
- How many times: Once per insert, but the search depends on the size of the referenced table.
The search to verify the key usually uses an index, making it fast even if the table grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 3-4 steps to find the key |
| 100 | About 7 steps |
| 1000 | About 10 steps |
Pattern observation: The number of steps grows slowly, not directly with the number of rows.
Time Complexity: O(log n)
This means the check gets a little slower as the referenced table grows, but it stays efficient.
[X] Wrong: "Checking a FOREIGN KEY is as slow as scanning the whole referenced table every time."
[OK] Correct: Databases use indexes to find keys quickly, so they don't scan the whole table.
Understanding how FOREIGN KEY checks scale shows you know how databases keep data correct without slowing down too much.
"What if the referenced column does not have an index? How would the time complexity change?"
Practice
FOREIGN KEY constraint in a database?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]
- Confusing FOREIGN KEY with indexing
- Thinking FOREIGN KEY stores data
- Assuming FOREIGN KEY backs up data
Orders referencing Customers(CustomerID)?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]
- Using PRIMARY KEY instead of FOREIGN KEY
- Omitting parentheses around column name
- Using TO instead of REFERENCES keyword
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?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]
- Assuming insert sets foreign key to NULL automatically
- Thinking insert triggers only warnings, not errors
- Believing insert succeeds without parent key
CREATE TABLE Orders (OrderID INT PRIMARY KEY, CustomerID INT, FOREIGN KEY CustomerID REFERENCES Customers(CustomerID));What is wrong with this statement?
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]
- Omitting parentheses around foreign key columns
- Thinking PRIMARY KEY conflicts with FOREIGN KEY
- Misunderstanding REFERENCES usage
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?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]
- Assuming delete fails due to existing child rows
- Thinking child rows remain with broken references
- Confusing CASCADE with SET NULL behavior
