SQL ยท Chapter 27 of 42
SQL EXISTS
`EXISTS (subquery)` returns TRUE if the subquery returns at least one row. Perfect for existence checks.
Often faster than IN, and safer with NULLs.
vs IN
IN materialises the whole list. EXISTS stops at the first match. On big subquery results, EXISTS is usually faster.
Example 1 (sql)
SELECT name FROM users u
WHERE EXISTS (
SELECT 1 FROM orders o WHERE o.user_id = u.id
);Output
users with at least one orderThe subquery selects `1` because we only care that SOMETHING exists.
Example 2 (sql)
SELECT name FROM users u
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.user_id = u.id
);Output
users with zero ordersNOT EXISTS = anti-join, NULL-safe.
Key points
- EXISTS = 'does at least one row exist?'
- Return `1` inside โ column doesn't matter.
- NOT EXISTS is safer than NOT IN with NULLs.
- Often faster than IN on big subqueries.
๐ก Note: `SELECT 1` and `SELECT *` are equivalent inside EXISTS โ the database ignores the column list.
