Exists check

2 snippets in SQL

Also written as check existence

SQLSQL

EXISTS

SQL · Filtering
Syntax
WHERE EXISTS (subquery)
Example
SELECT u.first_name, u.email
FROM users u
WHERE EXISTS (
  SELECT 1 FROM orders o
  WHERE o.user_id = u.id
  AND o.total_amount > 500
);
Output
-- Users who have at least one order over 500

Note EXISTS stops scanning as soon as it finds one matching row, making it efficient. It generally outperforms IN with large subquery results. The SELECT list inside EXISTS is irrelevant - SELECT 1 is conventional.

EXISTS Subquery

SQL · Subqueries
Syntax
WHERE EXISTS (SELECT 1 FROM table WHERE condition)
Example
SELECT c.category_name
FROM categories c
WHERE NOT EXISTS (
  SELECT 1 FROM products p
  WHERE p.category_id = c.id
);
Output
-- Categories that have no products at all

Note NOT EXISTS is the safest way to find missing related rows. Unlike NOT IN, it handles NULLs correctly and will not produce unexpected empty results.

Frequently asked questions

How does SQL handle exists check?
SQL covers this with 2 copy-ready snippets on this page. The "EXISTS" snippet in SQL uses `WHERE EXISTS (subquery)`.
Which statement does the SQL example use?
The "EXISTS" snippet uses `WHERE EXISTS (subquery)`, from the Filtering section of the SQL cheat sheet.
What other SQL snippets are shown for "exists check"?
Besides "EXISTS", this page also shows "EXISTS Subquery".
Is there anything to watch out for?
Yes. For "EXISTS": EXISTS stops scanning as soon as it finds one matching row, making it efficient. It generally outperforms IN with large subquery results. The SELECT list inside EXISTS is irrelevant - SELECT 1 is conventional.