T-SQL Tutorial

T-SQL Exists and NOT Exists


EXISTS

Subqueries with EXISTS are functional as a test to know whether or not something is present. Essentially an existence test. It doesn’t return any data and instead presents its results with TRUE or FALSE Boolean results.

NOT EXISTS

NOT EXISTS works in a similar way to EXISTS but there is also a difference. If the result of the subquery does not contain rows, NOT EXISTS returns as true. If a record in the table matches your subquery, NOT EXISTS will return false and the execution is halted.
Therefore, you should be able to instantly get an idea of the contents in your database by using this subquery to search.


Cities table:

CITY_IDNAMESTATE
1New YorkNew York
2Los AngelesCalifornia
3ChicagoIllinois
4San AntonioTexas
5San DiegoCalifornia

States table:

STATE_IDNAME
1Arizona
2California
3Texas
4Michigan

Exists Example:

Find the cities that have the column state correspondent in the states table.
SELECT * FROM cities c
WHERE EXISTS
(SELECT * FROM states s WHERE c.state=s.name );

Result:

CITY_IDNAMESTATE
2Los AngelesCalifornia
4San AntonioTexas
5San DiegoCalifornia

NOT Exists Example:

Find the cities that NOT have the column state correspondent in the states table.
SELECT * FROM cities c
WHERE NOT EXISTS
(SELECT * FROM states s WHERE c.state=s.name );

Result:

CITY_IDNAMESTATE
1New YorkNew York
3ChicagoIllinois