SQL: How do I delete rows that are also in another table?

2k Views Asked by At

Say I have two tables. E.g,

Table 1:

Store Product 
 1       2    
 1       1
 2       3
 2       4

And Table 2

Store Product 
 1       2    
 2       3

How do I delete all the rows in Table 1 that are also in Table 2?

So, new Table 1 would be:

Store Product 
 1       1
 2       4
2

There are 2 best solutions below

0
On BEST ANSWER

You seem want :

select t1.*
from table1 t1
where not exists (select 1 
                  from table2 t2
                  where t2.store = t.store and 
                        t2.product = t1.product
                 );

Similarly delete version would be :

delete 
from table1 t1
where exists (select 1 
              from table2 t2 
              where t2.store = t.store and 
                    t2.product = t1.product
             ); 
2
On

You can use something like this:

DELETE
    t1
FROM
    table1 t1
WHERE
    (t1.store, t1.product) IN ( SELECT 
                                     t2.store, 
                                     t2.product 
                                from 
                                    table2 t2);