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.
- Categoria
- Aggregates
- Returns
same type as the expression- In this category
- 5 of 52
Sintaxe
MAX(expression)
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sim | Supported under this name. |
| PostgreSQL | Sim | Supported under this name. |
| MySQL | Sim | Supported under this name. |
| SQLite | Sim | Supported under this name. |
| Oracle | Sim | Supported under this name. |
Exemplos
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;
Bom saber
- 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.
Related on SQLly
- Second-highest value Snippet
- Table dependency order for load and dump Snippet
- Detect missing days in date data Snippet
- List missing values in an id sequence Snippet
- Compute a checksum over a table Snippet
- SQL aggregation & HAVING interview questions Interview questions
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.