Given two tables departments and employees where employees.dept_id is a foreign key referencing departments.id with ON UPDATE CASCADE, what will be the dept_id values in employees after updating departments.id from 10 to 20?
CREATE TABLE departments (id INT PRIMARY KEY, name VARCHAR(50)); CREATE TABLE employees (id INT PRIMARY KEY, name VARCHAR(50), dept_id INT, FOREIGN KEY (dept_id) REFERENCES departments(id) ON UPDATE CASCADE); INSERT INTO departments VALUES (10, 'Sales'), (11, 'HR'); INSERT INTO employees VALUES (1, 'Alice', 10), (2, 'Bob', 11); UPDATE departments SET id = 20 WHERE id = 10; SELECT id, name, dept_id FROM employees ORDER BY id;
ON UPDATE CASCADE means changes to the parent key update the child keys automatically.
Because dept_id in employees has ON UPDATE CASCADE, when departments.id changes from 10 to 20, the corresponding dept_id in employees also updates from 10 to 20.
Consider tables orders and customers where orders.customer_id references customers.id with ON UPDATE SET NULL. What will be the customer_id values in orders after updating customers.id from 5 to 50?
CREATE TABLE customers (id INT PRIMARY KEY, name VARCHAR(50)); CREATE TABLE orders (id INT PRIMARY KEY, product VARCHAR(50), customer_id INT, FOREIGN KEY (customer_id) REFERENCES customers(id) ON UPDATE SET NULL); INSERT INTO customers VALUES (5, 'John'), (6, 'Jane'); INSERT INTO orders VALUES (101, 'Book', 5), (102, 'Pen', 6); UPDATE customers SET id = 50 WHERE id = 5; SELECT id, product, customer_id FROM orders ORDER BY id;
ON UPDATE SET NULL sets the foreign key to NULL if the referenced key changes.
When customers.id changes from 5 to 50, the orders.customer_id referencing 5 is set to NULL because of ON UPDATE SET NULL.
Which option contains a syntax error in defining a foreign key with an ON UPDATE action?
CREATE TABLE products ( id INT PRIMARY KEY, category_id INT, FOREIGN KEY (category_id) REFERENCES categories(id) ON UPDATE ??? );
Check if the ON UPDATE action is a valid SQL keyword.
ON UPDATE DELETE is invalid syntax. The valid actions are CASCADE, SET NULL, SET DEFAULT, NO ACTION, and RESTRICT.
What happens if you try to update a primary key value in a parent table that has a foreign key referencing it with ON UPDATE RESTRICT and there are matching rows in the child table?
RESTRICT prevents changes that break referential integrity.
ON UPDATE RESTRICT forbids updating the parent key if child rows reference it, so the update fails with an error.
You have a large parent table categories and a child table items with a foreign key category_id referencing categories.id with ON UPDATE CASCADE. You need to update many categories.id values. Which approach is best to minimize performance impact?
Consider transaction overhead and cascading update behavior.
Updating all parent keys in one transaction triggers cascading updates efficiently and reduces locking overhead compared to multiple transactions or disabling constraints.