Bird
Raised Fist0
SQLquery~20 mins

Referential integrity enforcement in SQL - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Referential Integrity Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
What happens when deleting a parent row with ON DELETE CASCADE?

Given two tables departments and employees where employees.department_id references departments.id with ON DELETE CASCADE, what will be the result of deleting a department?

SQL
CREATE TABLE departments (id INT PRIMARY KEY, name VARCHAR(50));
CREATE TABLE employees (id INT PRIMARY KEY, name VARCHAR(50), department_id INT,
  FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE CASCADE);

INSERT INTO departments VALUES (1, 'HR'), (2, 'IT');
INSERT INTO employees VALUES (1, 'Alice', 1), (2, 'Bob', 2), (3, 'Charlie', 1);

DELETE FROM departments WHERE id = 1;

SELECT * FROM employees ORDER BY id;
AOnly the department row is deleted; employees remain
BDelete fails with foreign key constraint error
CRows with department_id = 1 are deleted; remaining employees: (2, 'Bob', 2)
DAll employees remain unchanged
Attempts:
2 left
💡 Hint

Think about what ON DELETE CASCADE means for child rows.

📝 Syntax
intermediate
2:00remaining
Which option correctly defines a foreign key with ON UPDATE SET NULL?

Choose the correct SQL statement to create a foreign key constraint that sets the child column to NULL when the parent key is updated.

AFOREIGN KEY (child_id) REFERENCES parent(id) ON UPDATE NO ACTION
BFOREIGN KEY (child_id) REFERENCES parent(id) ON UPDATE CASCADE
CFOREIGN KEY (child_id) REFERENCES parent(id) ON DELETE SET NULL
DFOREIGN KEY (child_id) REFERENCES parent(id) ON UPDATE SET NULL
Attempts:
2 left
💡 Hint

Focus on the ON UPDATE clause and the action SET NULL.

🔧 Debug
advanced
2:00remaining
Why does this foreign key constraint fail to create?

Given the following SQL, why does the foreign key constraint creation fail?

SQL
CREATE TABLE orders (
  order_id INT PRIMARY KEY,
  customer_id INT,
  FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE RESTRICT
);

CREATE TABLE customers (
  id INT PRIMARY KEY,
  name VARCHAR(100)
);
APrimary key must be declared on <code>customer_id</code> in <code>orders</code>
BThe referenced table <code>customers</code> must be created before <code>orders</code>
CThe <code>ON DELETE RESTRICT</code> clause is invalid syntax
DThe foreign key column <code>customer_id</code> must be declared NOT NULL
Attempts:
2 left
💡 Hint

Think about the order of table creation and foreign key references.

optimization
advanced
2:00remaining
How to optimize foreign key checks for bulk inserts?

You need to insert thousands of rows into a child table with foreign keys. Which approach optimizes performance while maintaining referential integrity?

ADisable foreign key checks before insert, then re-enable after all inserts
BInsert rows one by one with foreign key checks enabled
CDrop foreign key constraints permanently before insert
DInsert rows in any order without foreign key constraints
Attempts:
2 left
💡 Hint

Consider temporarily disabling checks to speed up bulk operations.

🧠 Conceptual
expert
2:00remaining
What is the effect of ON DELETE SET DEFAULT in referential integrity?

Consider a foreign key with ON DELETE SET DEFAULT. What happens when the referenced parent row is deleted?

AThe child foreign key column is set to its default value
BThe child row is deleted automatically
CThe delete operation is rejected with an error
DThe child foreign key column is set to NULL
Attempts:
2 left
💡 Hint

Think about what SET DEFAULT means for a foreign key column.

Practice

(1/5)
1. What is the main purpose of referential integrity in a database?
easy
A. To speed up query execution
B. To ensure relationships between tables remain consistent
C. To store large amounts of data efficiently
D. To create backup copies of the database

Solution

  1. Step 1: Understand referential integrity concept

    Referential integrity ensures that foreign keys in one table correctly reference existing rows in another table.
  2. Step 2: Identify the main purpose

    This prevents orphan records and keeps data relationships consistent and safe.
  3. Final Answer:

    To ensure relationships between tables remain consistent -> Option B
  4. Quick Check:

    Referential integrity = consistent relationships [OK]
Hint: Referential integrity means keeping table links correct [OK]
Common Mistakes:
  • Confusing referential integrity with performance optimization
  • Thinking it creates backups
  • Assuming it stores data efficiently
2. Which SQL statement correctly defines a foreign key with referential integrity enforcement?
easy
A. INSERT INTO Orders (OrderID, CustomerID) VALUES (1, 100);
B. CREATE TABLE Orders (OrderID INT, CustomerID INT PRIMARY KEY);
C. ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID);
D. SELECT * FROM Orders WHERE CustomerID = Customers.CustomerID;

Solution

  1. Step 1: Identify foreign key syntax

    The correct syntax to add a foreign key is using ALTER TABLE with ADD FOREIGN KEY referencing another table's column.
  2. Step 2: Check each option

    ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID); correctly adds a foreign key constraint. CREATE TABLE Orders (OrderID INT, CustomerID INT PRIMARY KEY); wrongly sets CustomerID as primary key without foreign key. INSERT INTO Orders (OrderID, CustomerID) VALUES (1, 100); is an insert, not a constraint. SELECT * FROM Orders WHERE CustomerID = Customers.CustomerID; is a select query, not a constraint definition.
  3. Final Answer:

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

    Foreign key syntax = ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID); [OK]
Hint: Foreign keys use ALTER TABLE ADD FOREIGN KEY ... REFERENCES [OK]
Common Mistakes:
  • Confusing primary key with foreign key syntax
  • Using INSERT or SELECT instead of constraint definition
  • Missing 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) ON DELETE CASCADE);

What happens if a customer with CustomerID = 5 is deleted?
medium
A. All orders with CustomerID = 5 are also deleted
B. The delete fails due to foreign key constraint
C. Orders with CustomerID = 5 remain unchanged
D. CustomerID in Orders is set to NULL for those orders

Solution

  1. Step 1: Understand ON DELETE CASCADE

    The ON DELETE CASCADE option means deleting a referenced row causes all related rows to be deleted automatically.
  2. Step 2: Apply to the scenario

    Deleting customer with CustomerID=5 will delete all orders linked to that customer in Orders table.
  3. Final Answer:

    All orders with CustomerID = 5 are also deleted -> Option A
  4. Quick Check:

    ON DELETE CASCADE = delete related rows [OK]
Hint: ON DELETE CASCADE deletes related rows automatically [OK]
Common Mistakes:
  • Thinking delete will fail due to constraint
  • Assuming related rows remain unchanged
  • Confusing CASCADE with SET NULL
4. You have this foreign key constraint:
FOREIGN KEY (ProductID) REFERENCES Products(ProductID) ON DELETE SET NULL

Which error will occur if you try to delete a product that is referenced by an order, but the ProductID column in Orders is defined as NOT NULL?
medium
A. Delete fails due to NOT NULL constraint violation
B. Delete succeeds and sets ProductID to NULL
C. Delete succeeds and removes the order row
D. Delete succeeds without affecting Orders

Solution

  1. Step 1: Understand ON DELETE SET NULL behavior

    This option sets the foreign key column to NULL in referencing rows when the referenced row is deleted.
  2. Step 2: Check NOT NULL constraint conflict

    If the foreign key column is NOT NULL, setting it to NULL violates the column constraint, causing the delete to fail.
  3. Final Answer:

    Delete fails due to NOT NULL constraint violation -> Option A
  4. Quick Check:

    SET NULL + NOT NULL column = delete fails [OK]
Hint: SET NULL fails if foreign key column is NOT NULL [OK]
Common Mistakes:
  • Assuming delete succeeds and sets NULL anyway
  • Thinking delete removes referencing rows
  • Ignoring NOT NULL constraint on foreign key
5. You want to enforce referential integrity between Employees and Departments tables. When a department is deleted, you want all employees in that department to be reassigned to department ID 0 (which means 'Unassigned'). Which foreign key option should you use?
hard
A. FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) ON DELETE RESTRICT
B. FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) ON DELETE CASCADE
C. FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) ON DELETE SET NULL
D. FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) ON DELETE SET DEFAULT

Solution

  1. Step 1: Understand ON DELETE SET DEFAULT

    This option sets the foreign key column to its default value when the referenced row is deleted.
  2. Step 2: Match requirement

    Since you want employees reassigned to department ID 0, set DepartmentID column default to 0 and use ON DELETE SET DEFAULT to assign that value automatically.
  3. Final Answer:

    FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) ON DELETE SET DEFAULT -> Option D
  4. Quick Check:

    Reassign on delete = ON DELETE SET DEFAULT [OK]
Hint: Use ON DELETE SET DEFAULT to assign default on delete [OK]
Common Mistakes:
  • Using CASCADE deletes employees instead of reassigning
  • Using SET NULL when column disallows NULL
  • Using RESTRICT blocks deletion