How to remove items that exist in one table from another?

I have tables A and B. Elements of table B may also exist in table A, and I want to delete these elements. What do the SQL expressions look like for this?

+4
source share
8 answers

this is an option

delete from a where a.key in (select key from b) 
+6
source

Or:

 DELETE a WHERE a.some_field IN (SELECT some_field FROM b) 

or

 DELETE A WHERE EXISTS (SELECT 1 FROM b WHERE b.field1 = a.field2) 

Depending on your database, you may find that one works especially better than the other. IIRC Oracle prefers that WHERE IS THERE EXISTS IN, but this may depend on a number of factors.

+3
source

Sort of:

 DELETE FROM TableA as A WHERE A.ID IN (SELECT ID FROM TableB AS B WHERE [your condition here]) 
+2
source

In some databases, the rather exotic look of DELETE FROM FROM is very effective.

 delete from foo from foo as f where exists ( select 1 from bar as b where b.field = f.field ) 
+2
source

If your tables use InnoDB, the easiest way would be to set table A with the foreign keys from table B and use ON DELETE CASCADE, thus, no code changes are required and the integrity of your database is guaranteed.

+1
source

This is permitted by standard.

 delete a from a join b on a.id = b.id; 
+1
source
 delete a --select a.* from tablea a join tableb b on a.someid = b.someid 

Make sure you first run the selection part to make sure you get the right entries.

0
source
 DELETE FROM FIRST_TABLE FT WHERE EXISTS( SELECT 1 FROM SECOND_TABLE ST WHERE ST.PRIMARY_KEY = FT.PRIMARY_KEY ); 
0
source

All Articles