Start learning free

LESSON 39 OF 66 · SQL: INTERVIEW QUESTIONS

Customers Who Bought Both in Python

Practice

An interviewer asks: "Which customers bought both the Mug and the Pen?" It sounds like WHERE … AND …, but one row of order_items holds one product, so no row is ever the Mug and the Pen at once. "Both" is a question about a customer's whole group of rows.

So you keep the rows that are either product, group them per customer, and count the different products in HAVING with COUNT(DISTINCT …). The same idea on another question, the customers who ordered on at least 2 different days:

SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING COUNT(DISTINCT ordered) >= 2

The Mug is product 1 and the Pen is product 4. The check adds two June orders for Dan Weber: a Pen in one, a Mug in the other. Chloe Ng bought the Mug twice and never the Pen, so counting rows with COUNT(*) would wrongly let her in. The query must print:

name
Ana Pop
Dan Weber
(2 rows)

Your task: in query, join customers, orders and order_items, keep the Mug and Pen rows, make one group per customer and keep the groups with 2 different products.


Assignment
Follow the Coding Tutorial to build the query one clause per line.


Hint
Keep the two products with IN (1, 4), group by customers.id (two customers can share a name) and count with COUNT(DISTINCT product_id).


STEP 1 OF 6
    Ctrl + Enter to check

    Sqlq Bought Both in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free