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.