0
0
SQLquery~5 mins

CASCADE delete preview in SQL

Choose your learning style9 modes available
Introduction
CASCADE delete preview helps you see which rows will be removed automatically when you delete a row that has related data in other tables.
When you want to delete a customer and also remove all their orders automatically.
When cleaning up data and you want to know what related records will be deleted.
Before deleting a product to see which sales records will be removed.
When managing parent-child relationships in tables and ensuring no orphan data remains.
Syntax
SQL
SELECT * FROM child_table WHERE foreign_key_column IN (SELECT primary_key_column FROM parent_table WHERE condition);
This query previews child rows linked to parent rows you plan to delete.
Replace child_table, foreign_key_column, parent_table, primary_key_column, and condition with your actual table and column names.
Examples
Shows all orders for customer with id 5 that will be deleted if the customer is deleted with CASCADE.
SQL
SELECT * FROM orders WHERE customer_id IN (SELECT id FROM customers WHERE id = 5);
Previews comments linked to post 10 that will be removed if the post is deleted.
SQL
SELECT * FROM comments WHERE post_id IN (SELECT id FROM posts WHERE id = 10);
Sample Program
This example creates two tables with a CASCADE delete rule. It inserts sample data and previews orders linked to customer 1 before deleting.
SQL
CREATE TABLE customers (id INT PRIMARY KEY, name VARCHAR(50));
CREATE TABLE orders (id INT PRIMARY KEY, customer_id INT, product VARCHAR(50),
  FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE);

INSERT INTO customers VALUES (1, 'Alice'), (2, 'Bob');
INSERT INTO orders VALUES (101, 1, 'Book'), (102, 1, 'Pen'), (103, 2, 'Notebook');

-- Preview orders that will be deleted if customer with id=1 is deleted
SELECT * FROM orders WHERE customer_id IN (SELECT id FROM customers WHERE id = 1);
OutputSuccess
Important Notes
CASCADE delete automatically removes related rows in child tables when a parent row is deleted.
Always preview with a SELECT query before deleting to avoid accidental data loss.
Not all databases support CASCADE delete; check your database documentation.
Summary
CASCADE delete preview shows which related rows will be removed automatically.
Use a SELECT query with IN and a subquery to find child rows linked to parent rows.
Previewing helps protect your data by confirming what will be deleted.