Skip to content
We areTOP 1%

Customers Who Bought All Products

MediumLeetCodeSQL: Subqueries & CTEs
Solve on LeetCode(opens in a new tab)
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews
Hint and exampleShow

This is relational division: group by the person and keep the groups whose COUNT(DISTINCT item) equals the total number of items, computed in a subquery.

Example: courses(code) and completed(student, code)

courses: C1, C2       completed
                      student | code
                      Asha    | C1
                      Asha    | C2
                      Asha    | C2
                      Ravi    | C1
SELECT student
FROM completed
GROUP BY student
HAVING COUNT(DISTINCT code) = (SELECT COUNT(*) FROM courses);
-- returns Asha

More in SQL: Subqueries & CTEs

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account