EXISTS and NOT EXISTS
EXISTS checks if a subquery returns any rows. It returns TRUE or FALSE.
Find departments that have employees:
NOT EXISTS finds the opposite - departments with no employees:
EXISTS vs IN:
EXISTSstops as soon as it finds one match (faster for large datasets)INchecks the entire listEXISTShandles NULLs correctly- Use
EXISTSfor correlated checks,INfor simple value lists
SELECT 1 is a convention - EXISTS only cares if rows exist, not what columns they contain.
Check your understanding
What does EXISTS do in a WHERE clause?
Examples run on the employees sample database. Open any of them in the playground to experiment.