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_ID | NAME | STATE |
---|---|---|
1 | New York | New York |
2 | Los Angeles | California |
3 | Chicago | Illinois |
4 | San Antonio | Texas |
5 | San Diego | California |
States table:
STATE_ID | NAME |
---|---|
1 | Arizona |
2 | California |
3 | Texas |
4 | Michigan |
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_ID | NAME | STATE |
---|---|---|
2 | Los Angeles | California |
4 | San Antonio | Texas |
5 | San Diego | California |
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_ID | NAME | STATE |
---|---|---|
1 | New York | New York |
3 | Chicago | Illinois |