SQL
Lab
Amazon Easy Frequently Asked Classic

Customers
Who Ordered
Every Product

Find customers who have ordered all available products.

Table Schema

Inspect
Table

interactive
ColumnTypeDescription
customer_idintegerCustomer identifier.
product_idintegerOrdered product identifier.
ColumnTypeDescription
product_idintegerProduct identifier.

Sample Data

Input
Output

Sample Input: products
product_id
1
2
3
Sample Input: orders
customer_idproduct_id
1011
1012
1013
1021
1022
1031
1032
1033
Expected Output
customer_id
101
103

SQL Editor

Run
Query

postgresql
Waiting for query

customer_id
101
103

Hints

Unlock
Clues

Hint 01: Count how many distinct products each customer ordered.
Hint 02: Compare that count to the total number of products.
Hint 03: Keep only customers whose product count matches the full catalog.

Solution

Locked
Answer

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

Step By
Step

01

Count the distinct products ordered by each customer.

02

Compare that count against the total number of products.

03

Keep only customers whose distinct product count matches the product table.

Related Questions

Keep
Solving