How does the EXISTS Clause work in SQL Server? -


i tried below queries , bit confused working of exists clause, although know evaluates true/false.

below #1 sql sub-query anyhow returns 0, still result of combined query 1.

1. select 1 exists ( select 0 1 = 1 )  2. select 1 exists ( select 0 1 = 0 ) 

also, if exists clause evaluates true/false, why below 1 not work?

select 1 exists ( 1 ) 

please me understand situation.

edit: exists clause evaluates true/false. condition true if sub-query returns result. why exists ( 1 ) not work ? true condition.

from documentation exists:

specifies subquery test existence of rows.

select 1  exists ( select 0 1 = 1 ) -- there row  select 1  exists ( select 0 1 = 0 ) -- no row returned subquery  select 1 exists ( 1 ) -- not valid query `1` not subquery 

keep in mind checks rows not values so:

select 1  exists ( select null 1 = 1 ) -- return 1 

livedemo

edit:

this seems contradictory sentence " exists clause evaluates true/false" ?

exists operator tests existence of rows , returns true/false.

so if subquery returns:

╔══════════╗     ╔══════════╗     ╔══════════╗     ╔══════════╗ ║ subquery ║     ║ subquery ║     ║ subquery ║     ║ subquery ║ ╠══════════╣     ╠══════════╣     ╠══════════╣     ╠══════════╣ ║ null     ║     ║ 1        ║     ║ 0        ║     ║anything  ║ ╚══════════╝     ╚══════════╝     ╚══════════╝     ╚══════════╝ 

then exists (subquery) -> true.

if subquery returns (no rows):

╔══════════╗ ║ subquery ║ ╚══════════╝ 

then exists (subquery) -> false.


Comments