Search code examples
sqlsql-serversubquerywhere-clause

Where with exists how it works in subselect with variable without link


I have a question about the EXISTS clause: I have a query using it, but with code I have never seen.

In the WHERE of subselect, I see this expression:

WHERE 
    @var IS NULL 
    OR EXISTS(another subselect)

But this variable cannot do link with his select and subselect.

How does this work?


Solution

  • where @var is null is a boolean condition

    if @var is null, then it's true - else false.

    or exists (select '' from table t 
               where t.id = s.id and date > '2012-12-1')
    

    returns true, if at least one row exists for the subquery.

    If @var is not null, then exists is evaluated for a true condition