EXISTS and NOT EXISTS
The EXISTS and NOT EXISTS operators are used to check whether a subquery returns any rows.
They don’t evaluate the actual values from the subquery — only whether rows are returned.
Syntax
The basic syntax for EXISTS and NOT EXISTS is as follows:
SELECT ...
FROM table
WHERE EXISTS (
SELECT 1
FROM another_table
WHERE condition
);
EXISTS: returnsTRUEif the subquery returns at least one rowNOT EXISTS: returnsTRUEif the subquery returns zero rows
Example 1: Users Who Selected Any Courses
Find all users who have at least one course in user_courses.
SELECT name
FROM users u
WHERE EXISTS (
SELECT 1
FROM user_courses uc
WHERE uc.user_id = u.user_id
);
The subquery in the WHERE clause ensures the users table only returns those with at least one course.
Output:
| name |
|---|
| Sofia |
| Ethan |
| Aisha |
| Olivia |
| Liam |
All users have at least one course, so all of them are returned.
Example 2: Users who didn't take any courses
To find users who didn't take any courses, use NOT EXISTS.
For example, since Olivia has no entries in user_courses, the query would return her:
SELECT name
FROM users u
WHERE NOT EXISTS (
SELECT 1
FROM user_courses uc
WHERE uc.user_id = u.user_id
);
Output:
| name |
|---|
| Olivia |
NOT EXISTSreturns only users who have no matching rows inuser_courses.
Why Use EXISTS?
- Often more efficient than
IN, especially with large or correlated subqueries - Great for presence/absence checks
- Improves readability for permission checks, conditional joins, or business rules
Tip: Use
EXISTSwhen you care about the presence of a row, not the value itself.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.