Database Design
SQL Constraints
Foreign Keys
ON UPDATE
ON DELETE

Foreign key constraints When to use ON UPDATE and ON DELETE

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Foreign key constraints are essential components in relational databases, designed to maintain data integrity and establish relationships between tables. One of the core features of foreign keys is their ability to define actions on related data when primary key data is updated or deleted. This article delves into the intricacies of using ON UPDATE and ON DELETE clauses, explaining when and why you'd want to use these features.

Understanding Foreign Key Constraints

Before diving into ON UPDATE and ON DELETE, it is essential to understand the role of foreign key constraints. A foreign key in one table points to a primary key in another table, establishing a connection between the two tables. This relationship enforces referential integrity, ensuring that relationships between tables remain consistent.

Example of Foreign Key Constraint

Consider two tables: Orders and Customers. An Order is linked to a Customer through a foreign key:

sql
1CREATE TABLE Customers (
2    CustomerID INT PRIMARY KEY,
3    Name VARCHAR(100)
4);
5
6CREATE TABLE Orders (
7    OrderID INT PRIMARY KEY,
8    OrderDate DATE,
9    CustomerID INT,
10    CONSTRAINT FK_CustomerOrder FOREIGN KEY (CustomerID)
11    REFERENCES Customers(CustomerID)
12);

In this setup, the CustomerID column in the Orders table is a foreign key referencing the CustomerID column in the Customers table.

ON UPDATE Clause

Purpose of ON UPDATE

The ON UPDATE clause is employed to define actions that occur automatically to dependent rows when the primary key of a referenced row is updated. This can help maintain consistency and prevent orphaned data.

When to Use ON UPDATE

  • Cascading Changes: Use ON UPDATE CASCADE when changes to a primary key should be reflected across all related rows. This is useful for situations where primary key values are meaningful and subject to change.
  • Restrict Changes: Use ON UPDATE RESTRICT to prevent updates to a key if related rows exist; this is the default behavior.
  • Set to Null or Default: Using SET NULL or SET DEFAULT can be helpful when you prefer that dependent rows should not maintain foreign key values post-update, effectively severing the relationship.

Example of Using ON UPDATE

sql
1ALTER TABLE Orders
2ADD CONSTRAINT FK_CustomerOrder
3FOREIGN KEY (CustomerID)
4REFERENCES Customers(CustomerID)
5ON UPDATE CASCADE;

This ensures that if a CustomerID is updated in the Customers table, the change cascades to the Orders table, updating all related CustomerID values.

ON DELETE Clause

Purpose of ON DELETE

The ON DELETE clause defines the behavior of foreign key relationships when a referenced row in the parent table is deleted. This helps manage data integrity by determining what happens to dependent rows.

When to Use ON DELETE

  • Cascading Deletes: Use ON DELETE CASCADE if deleting a parent row should automatically delete dependent rows. This is often used when dependent data is meaningless without the parent data.
  • Restrict Deletions: With ON DELETE RESTRICT, you can prevent deletes of parent rows if child rows exist.
  • Set to Null or Default: Use SET NULL or SET DEFAULT when you want to preserve dependent rows but remove the foreign key relationship.

Example of Using ON DELETE

sql
1ALTER TABLE Orders
2ADD CONSTRAINT FK_CustomerOrder
3FOREIGN KEY (CustomerID)
4REFERENCES Customers(CustomerID)
5ON DELETE SET NULL;

In this example, if a customer is deleted, the CustomerID in related orders is set to NULL, maintaining the orders while acknowledging the loss of a corresponding customer.

Key Considerations and Summary

The table below summarizes the key behaviors associated with ON UPDATE and ON DELETE.

ClauseActionDescription
ON UPDATE CASCADEUpdateUpdates foreign key columns to match the new primary key value.
ON DELETE CASCADEDeleteDeletes rows with foreign keys referencing the deleted primary key.
ON UPDATE RESTRICTRestrictPrevents the UPDATE operation if there are dependent foreign key rows.
ON DELETE RESTRICTRestrictPrevents the DELETE operation if there are dependent foreign key rows.
SET NULLNullificationSets the foreign key column to NULL upon update/delete of the referenced key.
SET DEFAULTDefault ValueSets the foreign key column to its default value upon update/delete of the referenced key.

Additional Considerations

  • Data Integrity: Always consider how operations should impact related data to maintain integrity.
  • Business Logic: Align the use of ON UPDATE and ON DELETE with the business logic and rules of your application.
  • Performance: Cascading actions can have performance implications, especially with extensive data relationships.

By understanding and appropriately using ON UPDATE and ON DELETE clauses, database designers and developers can effectively manage relationships and ensure data consistency in their applications.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.