Introduction
Foreign key ON DELETE behavior controls what happens to related data when a record is deleted. It helps keep data correct and avoids broken links.
Jump into concepts and practice - no test required
FOREIGN KEY (child_column) REFERENCES parent_table(parent_column) ON DELETE action
FOREIGN KEY (order_customer_id) REFERENCES customers(customer_id) ON DELETE CASCADE
FOREIGN KEY (order_product_id) REFERENCES products(product_id) ON DELETE SET NULL
FOREIGN KEY (employee_id) REFERENCES employees(id) ON DELETE RESTRICT
CREATE TABLE customers ( customer_id INT PRIMARY KEY, name VARCHAR(50) ); CREATE TABLE orders ( order_id INT PRIMARY KEY, order_customer_id INT, FOREIGN KEY (order_customer_id) REFERENCES customers(customer_id) ON DELETE CASCADE ); INSERT INTO customers VALUES (1, 'Alice'), (2, 'Bob'); INSERT INTO orders VALUES (101, 1), (102, 1), (103, 2); DELETE FROM customers WHERE customer_id = 1; SELECT * FROM orders ORDER BY order_id;
ON DELETE CASCADE option do in a foreign key constraint?ON DELETE SET NULL in SQL?ON DELETE SET NULL after the foreign key reference.CREATE TABLE parent (id INT PRIMARY KEY);
CREATE TABLE child (id INT PRIMARY KEY, parent_id INT, FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE RESTRICT);
INSERT INTO parent VALUES (1);
INSERT INTO child VALUES (10, 1);
DELETE FROM parent WHERE id = 1;?ALTER TABLE child ADD CONSTRAINT fk_parent FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE SET NULL;
parent_id does not become NULL. What is the likely problem?parent_id is NOT NULL, the database cannot set it to NULL, so it leaves it unchanged.parent_id column is NOT NULL, so it cannot be set to NULL. -> Option CCREATE TABLE orders (order_id INT PRIMARY KEY);
CREATE TABLE order_items (item_id INT PRIMARY KEY, order_id INT, FOREIGN KEY (order_id) REFERENCES orders(order_id) ON DELETE CASCADE);
order_items.order_id can be NULL for items not linked to any order. What is the best ON DELETE behavior to use for the foreign key to avoid errors and keep data consistent?