Medium Aggregates and GROUP BY Shop database

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

Press Run to see your query's result, or Check answer to compare it with the expected result.

Expected result

categorylowesthighest
Accessories19.949.9
Displays189189
Video5959

Rows can come in any order. Column names do not have to match.

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.

Want to try the query on MySQL or PostgreSQL? Open it in the SQL Online Compiler or SQLite Online.