// 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.

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

语法

MAX(expression)

引擎支持

引擎Support备注
SQL Server 是 Supported under this name.
PostgreSQL 是 Supported under this name.
MySQL 是 Supported under this name.
SQLite 是 Supported under this name.
Oracle 是 Supported under this name.

示例

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;

值得了解

  • 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.