How to do an SQL Delete based on a Join

February 4, 2024 note-to-self

I'm mostly used to simple deletes using where clauses, but I know a DBA who prefers to use joins. To get more familiar, I've been doing simple stuff like that. The syntax between MS-SQL and MySQL is slightly different, but here's a note-to-self about doing it in MySQL.

I include START TRANS... all the way to above the COMMIT or ROLLBACK line and then once I find the number of rows deleted, I can commit or rollback, if there were any issues.

Instead of highlighting and running the DELETE, I can highlight the SELECT part and see how many rows to expect, and if the data looks good, etc.

START TRANSACTION;
DELETE s
-- SELECT s.id
FROM table1 s
    JOIN table2 h ON (s.table2_id = h.id)
    JOIN table3 r ON (h.table3 = r.id)
    JOIN events e ON (r.event_id = e.id)
    WHERE e.zzz_event_id IN (55454, 64957)
; -- 37,948
-- COMMIT or ROLLBACK

START TRANSACTION;
DELETE h
-- SELECT h.id
FROM table2 h
    JOIN table3 r ON (h.table3 = r.id)
    JOIN events e ON (r.event_id = e.id)
    WHERE e.zzz_event_id IN (55454, 64957)
; -- 10,105
-- COMMIT or ROLLBACK
START TRANSACTION;

DELETE r
-- SELECT r.id
FROM table3 r
    JOIN events e ON (r.event_id = e.id)
    WHERE e.zzz_event_id IN (55454, 64957)
; -- 562
-- COMMIT or ROLLBACK