Table Schema
Inspect
Table
| Column | Type | Description |
|---|---|---|
| customer_id | integer | Customer identifier. |
| product_id | integer | Ordered product identifier. |
| Column | Type | Description |
|---|---|---|
| product_id | integer | Product identifier. |
Find customers who have ordered all available products.
Table Schema
| Column | Type | Description |
|---|---|---|
| customer_id | integer | Customer identifier. |
| product_id | integer | Ordered product identifier. |
| Column | Type | Description |
|---|---|---|
| product_id | integer | Product identifier. |
Sample Data
| product_id |
|---|
| 1 |
| 2 |
| 3 |
| customer_id | product_id |
|---|---|
| 101 | 1 |
| 101 | 2 |
| 101 | 3 |
| 102 | 1 |
| 102 | 2 |
| 103 | 1 |
| 103 | 2 |
| 103 | 3 |
| customer_id |
|---|
| 101 |
| 103 |
SQL Editor
| customer_id |
|---|
| 101 |
| 103 |
Hints
Solution
Solution is locked until you decide to reveal it. Try the editor first, then open this when you want the reference answer.
SELECT customer_id FROM orders GROUP BY customer_id HAVING COUNT(DISTINCT product_id) = ( SELECT COUNT(*) FROM products ) ORDER BY customer_id;
Explanation
Count the distinct products ordered by each customer.
Compare that count against the total number of products.
Keep only customers whose distinct product count matches the product table.
Related Questions