Customers Who Bought All Products
Find customers who have purchased every product in the catalogue.
Start practiceProblem statement
Prompt
Given the customer and product tables below, write a query that returns the customer_id of every customer who has bought every product in the product table.
- Output a single column:
customer_id, ordered bycustomer_id. - Buying a product more than once does not help — each distinct product must appear.
Example
| customer_id | product_key |
|---|---|
| 1 | 5 |
| 1 | 6 |
| 2 | 5 |
| 2 | 6 |
| product_key |
|---|
| 5 |
| 6 |
Expected result:
| customer_id |
|---|
| 1 |
| 2 |
Constraints
customerhas no primary key; the same (customer, product) pair can repeat.product.product_keyis the primary key.
Tips
- Group by customer and require
COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM product). - This is the classic relational division problem.
Schema
CREATE TABLE customer (
customer_id INTEGER NOT NULL,
product_key INTEGER NOT NULL
);
CREATE TABLE product (
product_key INTEGER PRIMARY KEY
);
Sample data
INSERT INTO product (product_key) VALUES (5), (6);
INSERT INTO customer (customer_id, product_key) VALUES
(1, 5),
(1, 6),
(2, 5),
(2, 5), -- repeated purchase: still only product 5
(3, 6);
Additional hidden fixtures are applied during validation to test edge cases.
Solution
One correct approach — try solving it yourself in the practice editor first, then compare. There is usually more than one valid solution.
-- Reference: customers whose distinct purchases cover every product.
SELECT customer_id
FROM customer
GROUP BY customer_id
HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM product)
ORDER BY customer_id;
Key concepts
- HAVING COUNT(DISTINCT)
- Subquery
- Relational division
Related questions
- easyClasses With At Least 5 StudentsFind classes with five or more students enrolled.
- mediumDepartments by Average SalaryFind departments whose average salary is above the company average.
- easyDuplicate EmailsList the email addresses that appear more than once in the person table.
- easyActive Users Per DayReport the number of distinct active users for each date of activity.
- easyCustomers Without OrdersList customers who have never placed an order using an anti-join.