MIN() and MAX() Across Groups
Find the cheapest and most expensive product within each category.
Overview
MIN() and MAX() return the smallest and largest value of a column. With
GROUP BY they reveal the range inside each bucket: here, the lowest and highest
priced product per category in the store.
The Query
Loading playground environment...
Step-by-Step Breakdown
MIN(price)/MAX(price): the category's price floor and ceiling.MAX(price) - MIN(price): a derivedprice_spreadcolumn.GROUP BY category: ranges computed per category, not globally.
MIN/MAX on dates and text
These also work on dates (earliest/latest) and text (alphabetical first/last), not just numbers.
Variations
Find earliest and latest movie release per genre:
Loading playground environment...
Common Mistakes
- Confusing with LIMIT.
MIN(price)returns the value;ORDER BY price LIMIT 1returns the row. Use the aggregate when you only need the number. - NULL handling.
MIN/MAXignoreNULLs, which can hide missing data. - Non-grouped column in SELECT.
SELECT name, MIN(price)without groupingnameis invalid.
Cite this resource
SQLSimplified. "MIN() and MAX() Across Groups Example". Available at: https://sqlsimplified.online/examples/min-max