MAX example
SELECT MAX(total) AS largest_amount
FROM orders
WHERE status = 'shipped';It returns a value, not the order's data. To get the row, sort by amount and decide how to break ties.
What to look for: For example, if the shipped amounts are 18, 45 and 32, the result is 45. MAX answers “what is the highest value?”, not “which order has that value?”; they are different questions.
Check the result with small data
We want the largest amount among three orders.
WITH orders(id, total) AS (
VALUES (1, 12), (2, 40), (3, 25)
)
SELECT MAX(total) AS largest_total FROM orders;| largest_total |
|---|
| 40 |
MAX returns 40, the highest value, but on its own it does not tell you the order id. To get the whole row, sort by total and break ties.
Check your understanding: How would you get the order with both its id and total?
Show answer
By sorting and limiting: SELECT id, total FROM orders ORDER BY total DESC, id LIMIT 1. If you want every tied row, use WHERE total = (SELECT MAX(total) FROM orders).
What changes from case to case
MAX skips null values. If the filter leaves no known value, it returns NULL. That result can mean “no data”, not necessarily zero or an earliest date.
Common mix-ups with MAX
Combining MAX with a column it is not guaranteed to relate to
SELECT id, MAX(total) FROM orders does not reliably identify the order with the maximum. Use ORDER BY ... DESC with a limit or subquery that preserves ties.
Latest value, latest row and highest value are not the same
Usa MAX when you need the extreme value, such as each customer's latest order date. That does not automatically give you the status or amount of the order on that date, and two orders can share a date but have different statuses. To retrieve the record, decide whether you want every tied row or one chosen with a tiebreaker key.
Do not compute several maximums and assume they come from the same row. The largest amount may belong to an old order and the latest date to a smaller one; the two aggregates describe two independent extremes. A window function or a join to a summary can pick the row, but it must respect your tie policy.
Null values do not take part in the aggregate maximum; if there is no known value, the result is null. This matters for optional dates: a null maximum is not an implied start date. When comparing text, the order depends on the collation, so the code «9» can sort after «10». If the values represent quantities, validate and convert them before looking for the maximum.
Technical questions: PostgreSQL: aggregate functions (opens in a new tab).