Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all rows in a table based on another table

Tags:

sql

I can't seem to ever remember this query!

I want to delete all rows in table1 whose ID's are the same as in Table2.

So:

DELETE table1 t1  WHERE t1.ID = t2.ID 

I know I can do a WHERE ID IN (SELECT ID FROM table2) but I want to do this query using a JOIN if possible.

like image 712
mrblah Avatar asked Oct 19 '09 20:10

mrblah


People also ask

Can you remove rows from a table based on values from another table?

Example - Using EXISTS with the DELETE Statement You may wish to delete records in one table based on values in another table. Since you can't list more than one table in the FROM clause when you are performing a delete, you can use the EXISTS clause.

How do I delete a row in a table that contains foreign keys to other tables?

DELETE FROM ReferencingTable WHERE NOT EXISTS ( SELECT * FROM MainTable AS T1 WHERE T1. pk_col_1 = ReferencingTable. pk_col_1 ); Second, as a one-time schema-alteration exercise, add the ON DELETE CASCADE referential action to the foreign key on the referencing table e.g.

How do you delete a record from one table that matches another in MySQL?

MySQL also allows you to use the INNER JOIN clause in the DELETE statement to delete rows from a table and the matching rows in another table. Notice that you put table names T1 and T2 between the DELETE and FROM keywords. If you omit T1 table, the DELETE statement only deletes rows in T2 table.


1 Answers

DELETE t1  FROM Table1 t1 JOIN Table2 t2 ON t1.ID = t2.ID; 

I always use the alias in the delete statement as it prevents the accidental

DELETE Table1  

caused when failing to highlight the whole query before running it.

like image 79
HLGEM Avatar answered Oct 15 '22 04:10

HLGEM