Cheapest and most expensive per category
Question
For each product category, show the category, the lowest price and the highest price.
customersid, name, country, joined_on
productsid, name, category, price
ordersid, customer_id, ordered_on, status
order_itemsorder_id, product_id, quantity
Your query
Ctrl+Enter to run
Result
Expected result
| category | lowest | highest |
|---|---|---|
| Accessories | 19.9 | 49.9 |
| Displays | 189 | 189 |
| Video | 59 | 59 |
Hint
MIN() and MAX() work per group, like COUNT().
Show the solution
solution.sql
Run this code
SELECT category, MIN(price) AS lowest, MAX(price) AS highest
FROM products
GROUP BY category;
Why it works
Several aggregates can be calculated for the same groups at once. A category with one product has the same lowest and highest price.
Common mistake
Adding name to the SELECT does not tell you which product is the cheapest. SQLite would pick a name from the group, and other databases refuse the query. Use a join or a window function for that.