aggregate

MAX

Returns the largest non-NULL value in a group by the column's natural ordering. Useful for latest timestamps, top prices, or alphabetically last strings.

MAX(expression)

Parameters / Modifiers

Parameter Purpose
OVER (...) Windowed maximum across a partition
FILTER (WHERE ...) Postgres: conditional maximum
DISTINCT Accepted but redundant for MAX (kept for grammar symmetry)

Examples

SELECT MAX(paid_at) FROM invoices WHERE user_id = 7;

Latest payment timestamp for user 7

SELECT category, MAX(price) FROM products GROUP BY category;

Most expensive item per category

SELECT MAX(login_at) - MIN(login_at) FROM sessions;

Time span between first and last recorded login

SELECT MAX(CASE WHEN plan = 'pro' THEN 1 ELSE 0 END) FROM subs;

Portable 'has any pro row' flag using MAX over 0/1

Dialect notes / Gotcha

MAX over dates works but MAX(interval) is Postgres-only. For 'top-N' rows, ROW_NUMBER/RANK is usually cleaner than nested MAX subqueries.

Related functions

← All SQL functions · SQL cheat sheet · Window functions · PostgreSQL cheat sheet