// aggregates reference

SQL MAX function

Returns the largest non-null value in a group: the latest date, the highest amount. Like MIN, it returns a value, not the row the value came from.

Category
Aggregates
Returns
same type as the expression
In this category
5 of 52

Syntax

MAX(expression)

Engine support

EngineSupportNotes
SQL Server Yes Supported under this name.
PostgreSQL Yes Supported under this name.
MySQL Yes Supported under this name.
SQLite Yes Supported under this name.
Oracle Yes Supported under this name.

Examples

Any engine

SELECT MAX(created_at) AS last_order
FROM orders;

Any engine

SELECT customer_id, MAX(amount) AS biggest_order
FROM orders
GROUP BY customer_id;

Good to know

  • MAX ignores NULLs; MAX over only-NULL values returns NULL.
  • MAX(created_at) is the usual latest-record lookup, but combine it with a join carefully: two rows can share the same maximum timestamp.
  • On text columns the column's collation decides the winner. Under a case-insensitive collation, 'apple' and 'APPLE' tie, and either can come back.

Questions about MAX

How do I get the whole row with the maximum value?

An aggregate collapses the group, so pair MAX with a join, or use a window function: SELECT * FROM (SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rn FROM orders o) ranked WHERE rn = 1.

Does MAX ignore NULL?

Yes, the same as MIN. NULL values never win the maximum.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.