I have the following query:
select A, B from table1 where A in (select c from table 2 )
However, now I need to change this query and use exists
instead of in
, it should give the same result. My form looks like this:
table1 table2 A B c ------ ----- 1 x 1 2 y 3 3 z 4 4 w 7 5 a 1 b
How to use exists
functions?
You need to match exists
the two columns that will be used in:
select t1.a, t1.b from table1 t1 where exists (select 1 from table2 t2 where t2.c = t1.a)
The reason this has to be done is because exists
a semi-join is performed on the tables and thus needs to have a join condition.
This will be achieved by a direct inner join.
select t1.a, t1.b from table1 as t1 inner join table2 as t2 on t1.a=t2.c
Change the expression:
FROM Table1 WHERE a IN( SELECT c FROM Table2 )
EXISTS
Just a quick question:
- Add
SELECT
aWHERE
FROM Table1 WHERE a IN( SELECT c FROM Table2 WHERE )
- Move the outer match column (a) into the
SELECT
innerWHERE
clauseFROM Table1 WHERE IN( SELECT c FROM Table2 WHERE a )
- Move the inner matching column (b) to
WHERE
the clause, leaving the column placeholder (constant or *):FROM Table1 WHERE IN( SELECT * FROM Table2 WHERE a = c )
- will
IN
change toEXISTS
:FROM Table1 WHERE EXISTS( SELECT * FROM Table2 WHERE a = c )
- To be on the safe side, add the table name to the inner column:
FROM Table1 WHERE EXISTS( SELECT * FROM Table2 WHERE a = Table1.c )