MySQL MIN and MAX
MySQL MIN and MAX: Finding Extreme Column Values
The MySQL MIN() and MAX() aggregate functions return the smallest and largest non-NULL values in a column. Both functions work on numbers, dates, timestamps, and alphabetical strings.
Basic Syntax
Pass a column or expression into MIN() or MAX() inside a SELECT statement:
SELECT
MIN(price) AS lowest_price,
MAX(price) AS highest_price
FROM demo_products
WHERE is_active = 1;
If no rows match the WHERE filter, or if every matching row has NULL in that column, both MIN() and MAX() return NULL.
Practical SQL Examples
You can combine MIN() and MAX() with GROUP BY to compute price ranges for each product category in demo_products:
SELECT
category,
MIN(price) AS min_price,
MAX(price) AS max_price,
COUNT(*) AS item_count
FROM demo_products
WHERE is_active = 1
GROUP BY category
ORDER BY max_price DESC;
| category | min_price | max_price | item_count |
|---|---|---|---|
| Furniture | 189.00 | 499.00 | 6 |
| Electronics | 19.99 | 249.99 | 14 |
You can also inspect earliest and latest order timestamps per customer in demo_orders:
SELECT
customer_id,
MIN(created_at) AS first_order_at,
MAX(created_at) AS latest_order_at
FROM demo_orders
GROUP BY customer_id;
Common Mistakes and Best Practices
- Do Not Expect Other Columns Without
GROUP BY: WritingSELECT product_name, MIN(price) FROM demo_products;fails underONLY_FULL_GROUP_BYbecause MySQL does not know which product row corresponds to the minimum price. UseORDER BY price ASC LIMIT 1or a subquery to fetch the full winning row. - Index Columns Used in
MIN()/MAX(): When a column has a B-tree index, MySQL reads the first or last leaf entry instantly without scanning the whole table.
Frequently Asked Questions
Do MIN() and MAX() ignore NULL values?
Yes, both functions skip NULL values completely unless every row in the group is NULL, in which case they return NULL.
How do I get the entire row that has the maximum price?
Sort descending and take one row with ORDER BY price DESC LIMIT 1, or join against a MAX(price) subquery if ties are possible.
Can MIN() and MAX() work on text columns?
Yes, on string columns they compare values alphabetically using the column's collation rules.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.