user2133404
user2133404

Reputation: 1857

Delete Rows in a table Based on column value in third table

I have three tables Table1, Table2 and Table3 and the following query which deletes rows in Table1

delete from Table1 
where EXISTS
(select (1) from Table2
 where Table1.col1=Table2.col1
 AND   Table1.col2=Table2.col2
 AND   Table1.col3=(select **Table3.col3 from Table3** inner join Table2 on Table3.col1=Table2.col1)

Is this query correct? If not, how to use a third table inside the where condition?

Edit : Also, please explain how to rewrite the query if we want to delete the rows from table2 which itself is joined with table3?

Upvotes: 2

Views: 1136

Answers (1)

sgeddes
sgeddes

Reputation: 62831

Here's one way to do it:

delete from table1 
where (col1, col2, col3) in (
  select t1.col1, t1.col2, t1.col3
  from table1 t1
    join table2 t2 on t1.col1 = t2.col1 and t1.col2 = t2.col2
    join table3 t3 on t1.col3 = t3.col3 and t2.col1 = t3.col1
  );

Or using EXISTS might be faster:

delete table1 
where exists (
  select * 
  from table2
    join table3 on table2.col1 = table3.col1
  where table1.col3 = table3.col3 and 
    table1.col1 = table2.col1 and 
    table1.col2 = table2.col2);

Upvotes: 3

Related Questions