// window reference

SQL MIN and MAX with OVER

Finds the smallest or largest value in the frame or partition and attaches it to every row: running maxima for drawdowns, partition extremes for spreads.

Categoria
Janela
Returns
type of the expression
In this category
25 of 79

Sintaxe

MAX(x) OVER (PARTITION BY g) | MIN(x) OVER (ORDER BY d ROWS UNBOUNDED PRECEDING)

Suporte a mecanismos

MotorSupportNotas
SQL Server Sim Supported under this name.
PostgreSQL Sim Supported under this name.
MySQL Sim MySQL 8.0+
SQLite Sim SQLite 3.25+
Oracle Sim Supported under this name.

Exemplos

Any engine

SELECT day, price,
       MAX(price) OVER (ORDER BY day) AS running_high,
       price - MAX(price) OVER (ORDER BY day) AS off_high
FROM prices;

Any engine

SELECT department, salary,
       MIN(salary) OVER (PARTITION BY department) AS dept_min,
       MAX(salary) OVER (PARTITION BY department) AS dept_max
FROM employees;

Bom saber

  • MAX(x) OVER (ORDER BY d) is already a running maximum: the default frame ends at the current row (including its peers), which is exactly what a running high needs.
  • MIN/MAX ignore NULLs entirely; an all-NULL frame returns NULL, not an error.
  • For whole rows holding the extreme (not just the value), FIRST_VALUE with a matching ORDER BY or a ROW_NUMBER = 1 CTE is cleaner than MIN/MAX + join.

Questions about MIN and MAX with OVER

How do I get the row with the maximum value?

Filter with a window: rank rows ROW_NUMBER() OVER (PARTITION BY g ORDER BY x DESC) and keep rn = 1 in an outer query. MIN/MAX OVER only gives the value, and joining on x = MAX(x) keeps tied rows.

Do I need a frame clause for a running MAX?

Not when the ORDER BY is unique: the default RANGE frame already ends at the current row. With ties it includes the tied rows too, so two rows on the same day both see the day's high. Write ROWS UNBOUNDED PRECEDING plus a tiebreaker if each row must see only rows before it.

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

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

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