SQL EXISTS Function

Quick summary: The SQL EXISTS operator checks whether a subquery returns any rows.

SQL EXISTS Syntax

WHERE EXISTS (subquery)
SQL

SQL EXISTS Basic examples

SELECT * FROM users WHERE EXISTS (SELECT 1 FROM orders WHERE orders.user_id = users.id);
SQL
Output:
Users with at least one order

Filters rows based on subquery existence.

SQL EXISTS Real-world usage

SELECT * FROM products p WHERE EXISTS (SELECT 1 FROM stock s WHERE s.product_id = p.id AND s.qty > 0);
SQL
Output:
Products in stock

Efficient existence checks.

SQL EXISTS Edge cases

SELECT EXISTS (SELECT 1);
SQL
Output:
true

EXISTS returns true if subquery has rows.

SQL EXISTS Common mistakes

Using COUNT instead of EXISTS

COUNT scans all rows.

Incorrect
SELECT COUNT(*) FROM orders WHERE user_id = 5;
Correct
SELECT EXISTS (SELECT 1 FROM orders WHERE user_id = 5);

EXISTS stops at the first match.

SQL EXISTS Frequently Asked Questions

What does EXISTS do in SQL?

Checks if a subquery returns any rows.

Use case of EXISTS?

Filtering based on related data.

Returns value?

Boolean-like result.

Common mistake?

Using SELECT * inside EXISTS unnecessarily.

Performance advantage?

Stops at first match.

Difference from IN?

EXISTS is often faster for large datasets.

Supports correlated queries?

Yes.

Handles NULL?

Yes.

Used with WHERE?

Yes.

Best practice?

Use for existence checks.

Alternative?

IN.

Used in joins?

Indirectly.

SQL EXISTS Related SQL Keywords