CodeBlanks Logo Icon CodeBlanks

Constraint management

Add and drop constraints.

ON DELETE and ON UPDATE

With ON DELETE and ON UPDATE you set FOREIGN KEY behavior. Options are CASCADE, SET NULL and RESTRICT.

FOREIGN KEY (customer_id) REFERENCES customers(id)
  ON DELETE CASCADE

When the customer is deleted the orders are deleted too.

ON DELETE and ON UPDATE — details

CASCADE deletes/updates linked rows. SET NULL empties the linked column. RESTRICT blocks the delete. The default is RESTRICT.

Practice ON DELETE and ON UPDATE

Add customer_id FOREIGN KEY REFERENCES customers(id) ON DELETE CASCADE to orders.

Starter code

query.sql
-- add relation
CREATE TABLE orders (
  id INT PRIMARY KEY,
  customer_id INT,

Sample solution

query.sql
CREATE TABLE orders (
  id INT PRIMARY KEY,
  customer_id INT,
  FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE
)

Expected output

Tablo oluşturuldu

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Cascade

Question
FOREIGN KEY (cid) REFERENCES c(id) ON DELETE ____;
Answer
FOREIGN KEY (cid) REFERENCES c(id) ON DELETE CASCADE;

Explanation: CASCADE is the right answer.

2 Constraint management: match the terms

Term Meaning
CASCADE cascade
SET NULL set null
RESTRICT block
FOREIGN KEY relation

3 What does ON DELETE CASCADE do?

  • Sets the related rows to empty
  • Also deletes the related rows Correct answer
  • Keeps the related rows
  • Nothing

Explanation: CASCADE deletes linked rows too.

All lessons in Beginner