What is the difference between the EXISTS
and IN
clause in SQL?
When should we use EXISTS
, and when should we use IN
Which one is faster depends on the number of queries fetched by the inner query:
EXIST evaluate on true or false but IN compare multiple value. When you don't know the record is exist or not, your should choose EXIST
The Exists
keyword evaluates true or false, but IN
keyword compare all value in the corresponding sub query column.
Another one Select 1
can be use with Exists
command. Example:
SELECT * FROM Temp1 where exists(select 1 from Temp2 where conditions...)
But IN
is less efficient so Exists
faster.
I believe this has a straightforward answer. Why don't you check it from the people who developed that function in their systems?
If you are a MS SQL developer, here is the answer directly from Microsoft.
IN:
Determines whether a specified value matches any value in a subquery or a list.
EXISTS:
Specifies a subquery to test for the existence of rows.
The exists
keyword can be used in that way, but really it's intended as a way to avoid counting:
--this statement needs to check the entire table
select count(*) from [table] where ...
--this statement is true as soon as one match is found
exists ( select * from [table] where ... )
This is most useful where you have if
conditional statements, as exists
can be a lot quicker than count
.
The in
is best used where you have a static list to pass:
select * from [table]
where [field] in (1, 2, 3)
When you have a table in an in
statement it makes more sense to use a join
, but mostly it shouldn't matter. The query optimiser should return the same plan either way. In some implementations (mostly older, such as Microsoft SQL Server 2000) in
queries will always get a nested join plan, while join
queries will use nested, merge or hash as appropriate. More modern implementations are smarter and can adjust the plan even when in
is used.
I think,
EXISTS
is when you need to match the results of query with another subquery.
Query#1 results need to be retrieved where SubQuery results match. Kind of a Join..
E.g. select customers table#1 who have placed orders table#2 too
IN is to retrieve if the value of a specific column lies IN
a list (1,2,3,4,5)
E.g. Select customers who lie in the following zipcodes i.e. zip_code values lies in (....) list.
When to use one over the other... when you feel it reads appropriately (Communicates intent better).
If you are using the IN
operator, the SQL engine will scan all records fetched from the inner query. On the other hand if we are using EXISTS
, the SQL engine will stop the scanning process as soon as it found a match.