SQL: find orphaned rows before deleting
A regex example about dELETE FROM table1 WHERE NOT EXISTS (SELECT * FROM table2 WHERE table1.field1=table2.field1);.
Original example. NOT EXISTS handles missing related rows without the NULL behavior of NOT IN. Review foreign keys, the execution plan and the selected rows before deleting.
-- Inspect matches first. Replace example names with your schema. SELECT parent.* FROM table1 AS parent WHERE NOT EXISTS ( SELECT 1 FROM table2 AS child WHERE child.field1 = parent.field1 ); -- After reviewing the result and taking a backup, use the same -- predicate in a transaction. Verify affected rows before COMMIT. -- DELETE FROM table1 WHERE NOT EXISTS -- (SELECT 1 FROM table2 WHERE table2.field1 = table1.field1);