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?
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;
Think about what ON DELETE CASCADE means for child rows.
The ON DELETE CASCADE option means that when a referenced row in the parent table is deleted, all child rows referencing it are automatically deleted. So deleting department 1 removes employees with department_id = 1.
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.
Focus on the ON UPDATE clause and the action SET NULL.
The ON UPDATE SET NULL clause means that if the parent key changes, the foreign key in the child row is set to NULL. Option D correctly uses this syntax.
Given the following SQL, why does the foreign key constraint creation fail?
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) );
Think about the order of table creation and foreign key references.
Foreign key constraints require the referenced table to exist before the referencing table is created. Here, orders references customers which is created later, causing failure.
You need to insert thousands of rows into a child table with foreign keys. Which approach optimizes performance while maintaining referential integrity?
Consider temporarily disabling checks to speed up bulk operations.
Disabling foreign key checks temporarily allows faster bulk inserts. After inserts, re-enabling checks ensures integrity. Dropping constraints permanently risks data integrity.
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?
Think about what SET DEFAULT means for a foreign key column.
ON DELETE SET DEFAULT sets the foreign key column in the child row to its predefined default value when the referenced parent row is deleted.