MySQL MAX() Function
MySQL MAX() Function: Finding the Highest Value in a Column
The MAX() aggregate function returns the largest non-NULL value across rows in a column or expression. Unlike SUM() and AVG(), MAX() works on numbers, dates, timestamps, and text strings alike.
You will use MAX() to look up a customer's latest order date, the top salary in each department, or the highest unit price in a category. When paired with GROUP BY, it computes one peak value per group.
Syntax
MAX([DISTINCT] expr)
expr: Any comparable column or expression (numeric, date/time, or string).DISTINCT: Accepted by MySQL syntax, though it has no effect on the maximum value.
Practical Example
Suppose demo_orders stores customer orders with order_date, total_amount, and shipped_at. You can summarize each customer's biggest order and most recent order date in one grouped query.
SELECT
customer_id,
MAX(total_amount) AS largest_order,
MAX(order_date) AS latest_order_date,
MAX(shipped_at) AS latest_ship_date
FROM demo_orders
GROUP BY customer_id
ORDER BY largest_order DESC;
| customer_id | largest_order | latest_order_date | latest_ship_date |
|---|---|---|---|
| 105 | 1450.00 | 2026-04-12 | 2026-04-14 |
| 108 | 620.50 | 2026-04-18 | NULL |
| 112 | 299.00 | 2026-03-29 | 2026-03-31 |
Customer 108 has never had an order shipped (shipped_at is NULL on every row), so MAX(shipped_at) returns NULL while MAX(order_date) still succeeds.
Common Mistakes & NULL Behavior
- NULL values are ignored: If a group contains
(10, NULL, 40),MAX()ignoresNULLand returns40. It returnsNULLonly when every value in the group isNULLor zero rows match. - Fetching the full row of the maximum: Writing
SELECT product_name, MAX(price) FROM demo_productswithoutGROUP BYviolatesONLY_FULL_GROUP_BYor returns an arbitraryproduct_name. UseORDER BY price DESC LIMIT 1or a window functionROW_NUMBER()instead. - Text sorting on numeric strings: Running
MAX(code)onVARCHARvalues like'9'and'100'compares alphabetically and returns'9'. Cast numeric strings first when numeric order is intended.
Frequently Asked Questions
What does MAX() return on an empty table?
When no rows match (and there is no GROUP BY), MAX() returns a single row containing NULL.
How is MAX() different from GREATEST()?
MAX() finds the maximum vertically across multiple rows in one column and ignores NULLs. GREATEST() compares multiple expressions horizontally within one row and returns NULL if any argument is NULL.
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.