SQLPathLab
Subqueries · Intermediate

EXISTS

Checks whether a subquery returns at least one row.

Overview

EXISTS tests only whether a subquery returns at least one row; the selected values are irrelevant. A correlated subquery refers to the current outer row and is useful for checking whether related records exist. Neither EXISTS nor IN is universally faster, so choose clear semantics and verify with indexes and an execution plan.

Basic syntax

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

Examples

EXISTS example

Check each customer and keep only those with at least one related row in orders.

Sample table

Table:customers
customers
idnamecitystatusphonenickname
101 Alice New York active 138-0000-0001 NULL
102 Bob Seattle active NULL Bobby
103 Cindy Austin inactive 138-0000-0003 NULL
Table:orders
orders
idcustomer_idproduct_idnamedepartmentamountstatuscreated_atdiscount
1 101 201 Alice Sales 1200 paid 2026-01-03 0
2 102 202 Bob IT 900 pending 2026-01-08 50
3 101 201 Cindy Sales 1500 paid 2026-02-02 100
4 104 203 David HR 700 cancelled 2026-02-15 0

Run result

result
idnamecitystatusphonenickname
101 Alice New York active 138-0000-0001 NULL
102 Bob Seattle active NULL Bobby

Common issues

Does EXISTS care which columns the subquery returns?

No. EXISTS only checks whether the subquery returns at least one row.

When is EXISTS commonly used?

It is commonly used to check whether related records exist for a main-table row.

Is EXISTS always faster than IN?

No. Performance depends on data size, indexes, and the optimizer. Clarity comes first.

Tags

ConditionsCommonFiltering

Was this explanation clear?