Home / SQL / Reference / Subqueries, CTEs and sets

SQL EXISTS

True if a subquery returns at least one row.

Syntax

WHERE EXISTS (SELECT 1 FROM … WHERE …)

Usually correlated (it refers to the outer row). NOT EXISTS finds rows with no match and handles NULLs safely.

Example

Query (on the shop database used in the SQL course)

SELECT c.name
FROM customers AS c
WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id);

Result

name
Noah Brown
Kiran Rai
Anjali Karki

3 rows

Related

Learn it step by step in the free lesson Subqueries & Set Operations, with exercises that check your queries.