SQL EXISTS Operator
Here is a clear, practical, and complete guide to the SQL EXISTS operator, one of the most powerful tools for subquery filtering.
β
What EXISTS Does
EXISTS checks whether a subquery returns at least one row.
-
If the subquery returns a row β TRUE
-
If it returns no rows β FALSE
It is commonly used in correlated subqueries and is often faster and safer than IN or JOIN for existence checks.
πΉ Basic Syntax
π Basic Example β Users with at least one order
β Returns users only if they have an order.
π₯ Equivalent NOT EXISTS (missing relationships)
β Returns users with NO orders.
Very useful for finding βorphanβ records.
π₯ EXISTS vs. IN (Important Performance Note)
Using IN:
Using EXISTS:
Performance:
-
EXISTSstops scanning as soon as it finds one matching row. -
INmust compute and store the full list inside the subquery. -
EXISTSis safer if the subquery can return NULLs β avoidsNOT INpitfalls.
Rule of thumb:
β‘ Use EXISTS for correlated subqueries
β‘ Use IN for small, static lists
π§ Real-World Examples
1. Products that have reviews
2. Customers with late payments
3. Employees who manage at least one person
4. Orders with at least one expensive item
π§ Why Use SELECT 1 Inside EXISTS?
Anything inside EXISTS works:
Because SQL only checks whether a row exists, not what it contains.
Common convention = SELECT 1 (simplest & fastest).
π Performance Tips
β Use EXISTS for checking related rows
β Always correlate using indexed columns
β Avoid returning unnecessary columnsβuse SELECT 1
β NOT EXISTS is much safer than NOT IN (NULL issue)
