'Results for IN and EXISTS
I have two table Table_hold and table_pass and I am using the following query to find out if any id in Table_pass exists, then delete the same from Table_hold.
I am using below query:
delete from Table_hold
where EXISTS ( SELECT 1 FROM Table_pass pass
WHERE id = pass.id );
Is there something wrong with this query? Even though there is Id=4 in table_hold and it's not there in table_pass, it still it got deleted from table_hold.
Below are the dummy tables I created:
create table Table_pass(id1 number);
create table table_hold(id1 number);
insert into table_pass values(1);
insert into table_pass values(2);
insert into table_pass values(3);
insert into table_hold values(4);
delete from Table_hold
where EXISTS ( SELECT 1 FROM Table_pass pass
WHERE id1 = pass.id1 );
This query deletes one row with ID 4 in table_hold.
Solution 1:[1]
Qualify all column references!
delete from Table_hold
where exists (select 1
from Table_pass p
where p.id = table_hold.id
);
This subquery:
where EXISTS (SELECT 1
FROM Table_pass pass
WHERE id = pass.id
);
has a reference to id. How is it resolved? Well, from the inside out. So this is equivalent to:
where EXISTS (SELECT 1
FROM Table_pass pass
WHERE pass.id = pass.id
--------------------^ NOT table_hold
);
The solution is to get in the habit of qualifying all column names.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gordon Linoff |
