SQL Server › Constraints (Primary Key, Foreign Key, Check & Unique)

How do cascading actions work with foreign key constraints, such as ON DELETE CASCADE, and what risks come with using them?

Advanced

Answer

Cascading actions automatically apply a related change to child rows when the parent row is modified or deleted, such as automatically deleting all of a customer's orders when that customer is deleted, which can be convenient but also risky, since a single delete statement could unexpectedly remove far more data than intended if not carefully planned.
CREATE TABLE Orders (
  OrderId INT PRIMARY KEY,
  CustomerId INT,
  FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId) ON DELETE CASCADE
);
Real-world example A team enables ON DELETE CASCADE between customers and orders so that removing a test customer account automatically cleans up all of their related test orders without requiring several separate delete statements.

Common follow-ups: What other cascading actions are available besides CASCADE?;How do you audit which tables have cascading deletes configured before making a risky change?