EXISTS and NOT EXISTS
EXISTS checks whether a row exists
EXISTS does not care about a particular value returned by the subquery. Its question is simpler: did the inner query return at least one row?
SELECT u.id, u.name
FROM users AS u
WHERE EXISTS (
SELECT 1
FROM orders AS o
WHERE o.user_id = u.id
);
For each user, the query checks whether at least one related order exists. If such a row exists, the user remains in the result.
NOT EXISTS checks for the absence of a match
SELECT u.id, u.name
FROM users AS u
WHERE NOT EXISTS (
SELECT 1
FROM orders AS o
WHERE o.user_id = u.id
);
Now the result keeps users for whom the inner query found no orders.
With EXISTS, the existence of a row matters, not the expression after SELECT.
That is why
SELECT 1 is often used: it emphasizes that the selected values themselves are irrelevant.
Check yourself
Exercise review
The mentor knows the solution and will help you reach it independently
Sign in to use the Mentor
The Mentor uses the current exercise and your conversation history.
Sign in
Review the key nuances and the answer after making your own attempt.
Sign in to view the solution
The solution and explanation are available after signing in.
Sign in