DELAPARRA
Index
Color
NL
Category: SQL

EXISTS

Explained by Updated

What is EXISTS?

EXISTS: A boolean test — true if a subquery returns any row. Often faster than IN for large or correlated checks. EXISTS checks whether a subquery returns at least one row. WHERE EXISTS (SELECT 1 FROM orders WHERE orders.user_id = users.id) finds users who have placed an order. It stops as soon as it finds the first match, so it does not need to count or collect all matching rows. That often makes it faster than alternatives like IN with a large subquery or COUNT(*) > 0.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about EXISTS

What should you keep in mind with EXISTS?

NOT EXISTS is equally useful, for example to find customers who have never ordered. It also behaves sensibly with NULL values, unlike NOT IN, which returns no rows at all if the subquery contains a single NULL. Laravel's whereHas() and whereDoesntHave() generate EXISTS queries under the hood, which is why they are usually efficient.

What does an example of EXISTS look like?

SELECT name FROM users u WHERE EXISTS ( SELECT 1 FROM orders o WHERE o.user_id = u.id );

At a glance

CategorySQL
Explained by
Updated

More SQL terms

All terms starting with E

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.