SQL EXISTS

EXISTS returns true if a subquery returns at least one row. It is the cleanest way to ask "is there any related row?", for example departments that have a high earner.

NOT EXISTS is the safe way to find rows without a match, because unlike NOT IN it behaves correctly with NULLs.

Syntax

SELECT ... FROM a
WHERE EXISTS (SELECT 1 FROM b WHERE b.a_id = a.id);

Try it yourself

Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.

exists.sql · PostgreSQL
Loading editor…

Examples

1. EXISTS

SELECT name FROM departments d WHERE EXISTS (SELECT 1 FROM employees e WHERE e.department_id = d.id AND e.salary > 100000);

Departments with a six-figure salary.

2. NOT EXISTS

SELECT id, first_name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

Customers with no orders.

Common mistakes

  • Forgetting to correlate the subquery with the outer table, so EXISTS is true for every row.

Practice: test yourself

This challenge is from our interactive course. Write the query and press Check answer.

Challenge · 30 pts

Return the name of every department that has at least one employee earning over 100000.

challenge.sql · PostgreSQL
Loading editor…

FAQ

What should I SELECT inside EXISTS?

It doesn't matter; SELECT 1 is the convention.

Learn SQL step by step

65 hands-on exercises, streaks, a leaderboard and a certificate.

Start free →