Wednesday, August 29, 2012

Difference between IN and EXISTS


S.NoINEXISTS
1Returns true if specified value matches any value in the sub query or a list.Return true if sub query contain any rows.
2The sub query will run first and then only outer query.The Outer query will ran first and then only sub query.
3IN is slower than EXISTS. The IN is used in the widely For Static variables for eg: select name from table where ID in (Select ID from table2).Exists is faster than IN.The Outer query will run first and then only inner query.So it will reduce the over head. The Exists is useful mostly in IF conditional statements.
4
Example:

SELECT id,
[Name]
FROM dbo.tablea
WHERE id IN (SELECT id
FROM dbo.tableb)
Example:

SELECT id,
[Name]
FROM dbo.tablea AS a
WHERE EXISTS (SELECT id2
FROM dbo.tableb
WHERE id2 = a.id)

No comments:

Post a Comment