MySQL GREATEST() Function
MySQL GREATEST() Function: Finding the Largest Value Across Arguments
The GREATEST() function returns the largest value from a list of two or more arguments in the same row. Unlike MAX(), which aggregates vertically across multiple rows, GREATEST() compares horizontally across columns or expressions.
It works on numbers, strings, and date/time values. Developers rely on GREATEST() to enforce minimum floors (such as GREATEST(0, balance)), pick the latest timestamp among several columns, or find the highest bid across columns.
Syntax
GREATEST(value1, value2, ...)
value1, value2, ...: Two or more expressions to compare. Passing fewer than two arguments causes an error.
Practical Example
Suppose demo_orders tracks three independent date milestones: created_at, updated_at, and shipped_at (which may be NULL for unshipped orders). You want each order's most recent activity date without letting NULL wipe out the comparison.
SELECT
order_id,
created_at,
updated_at,
shipped_at,
GREATEST(
created_at,
COALESCE(updated_at, created_at),
COALESCE(shipped_at, created_at)
) AS latest_activity
FROM demo_orders
WHERE order_id BETWEEN 801 AND 803;
| order_id | created_at | updated_at | shipped_at | latest_activity |
|---|---|---|---|---|
| 801 | 2026-03-01 | 2026-03-04 | 2026-03-05 | 2026-03-05 |
| 802 | 2026-03-02 | 2026-03-06 | NULL | 2026-03-06 |
| 803 | 2026-03-03 | NULL | NULL | 2026-03-03 |
Wrapping nullable columns in COALESCE() keeps order 802 and 803 from turning completely NULL.
Common Mistakes & NULL Behavior
- One NULL ruins the whole call: In MySQL,
GREATEST()returnsNULLif any argument isNULL(GREATEST(10, 50, NULL)returnsNULL). This differs fromMAX(), which ignoresNULLs, and differs from PostgreSQL'sGREATEST(). Always wrap nullable inputs withCOALESCE(). - Passing only one argument: Calling
GREATEST(price)fails with a parameter count error. Supply at least two arguments. - Mixing numbers and strings: Comparing
GREATEST(10, '200')converts'200'to a number (200), whereasGREATEST('10', '200')compares lexicographically ('200'). Keep argument types consistent.
Frequently Asked Questions
What is the difference between GREATEST() and MAX() in MySQL?
MAX() is an aggregate function that finds the highest value in one column across many rows (ignoring NULLs). GREATEST() compares multiple values in a single row and returns NULL if any argument is NULL.
How can I ignore NULLs inside GREATEST()?
Wrap each nullable column with COALESCE(col, fallback), choosing a tiny sentinel value like -999999 or '1900-01-01' (or another non-NULL column).
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.