Return customerids that have purchased BOTH product AlphaPad and product BetaPhone. Table definitions (from the source…
SQLLevel: IntermediateMembership and set logic
Return customer_ids that have purchased BOTH product AlphaPad and product BetaPhone.
Table definitions (from the source exercise):
CREATE TABLE products(product_id INTEGER PRIMARY KEY, product_name TEXT, category TEXT, price REAL);
CREATE TABLE orders(order_id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT, amount REAL, rep_id INTEGER, discount REAL);
CREATE TABLE order_items(item_id INTEGER PRIMARY KEY, order_id INTEGER, product_id INTEGER, quantity INTEGER);
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
Approach: Filter to the two names, group by customer, HAVING COUNT(DISTINCT product) = 2.
SELECT o.customer_id
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE p.product_name IN ('AlphaPad', 'BetaPhone')
GROUP BY o.customer_id
HAVING COUNT(DISTINCT p.product_name) = 2;
The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.
Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT