I’ve seen the EXISTS keyword in Microsoft SQL Server T-SQL code and don’t understand it well. What does it do? How do I use it? Are there best practices around SQL EXISTS?
This SQL tutorial will explain what the keyword EXISTS does and show several different use cases.
Read on to see how you can use EXISTS
and its complement, NOT EXISTS
, in a variety of use cases. One important part of why EXISTS
can be useful compared to other ways of writing a particular query is that the performance profile of an EXISTS
clause is a semi-join: we proceed until we find the first result matching our clause. If that happens to be in the first row, we can stop there as we’ve fulfilled the requirement. By contrast, an alternative using IN
or something else like using SELECT COUNT(*)
would likely need to read more pages of data than EXISTS
.