Search code examples
sqlteradataanti-join

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


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

Solution

  • 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
                 );