iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

SQL EXISTS

EXISTS tests whether a subquery returns any rows. It returns TRUE as soon as one match is found — without scanning the rest.

Example

SQL
SELECT c.name
FROM customers c
WHERE EXISTS (
  SELECT 1
  FROM orders o
  WHERE o.customer_id = c.id
    AND o.total > 1000
);

"Show every customer who has at least one order over $1,000".

SELECT 1 is conventional

What the inner SELECT returns doesn't matter — only whether there's any row. SELECT 1, SELECT *, and SELECT NULL all behave identically. Most teams use SELECT 1 as a hint to the reader.

EXISTS vs IN

FormNotes
WHERE x IN (subquery)Easier to read for single-column lookups.
WHERE EXISTS (subquery)Safe with NULLs. Often faster for "is there at least one?" checks.

NOT EXISTS — the safe anti-join

SQL
-- Customers who have never placed an order
SELECT c.*
FROM customers c
WHERE NOT EXISTS (
  SELECT 1 FROM orders o WHERE o.customer_id = c.id
);

NOT EXISTS is the safest alternative to NOT IN when NULLs are possible.

Tip: Correlated subqueries inside EXISTS look expensive but are usually well-optimised. Modern planners rewrite EXISTS into a semi-join.

Example

Example
SELECT name FROM customers c
WHERE EXISTS (
  SELECT 1 FROM orders o WHERE o.customer_id = c.id
);
Try it Yourself »

Exercise

Use EXISTS to test whether any matching order exists.

WHERE (SELECT 1 FROM orders o WHERE o.customer_id = c.id)

Test yourself

Q1. EXISTS returns true when…
Q2. Most teams write…
Q3. NOT EXISTS is preferred over NOT IN when…

Discussion

Loading…