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.
- 카테고리
- 창
- Returns
type of the expression- In this category
- 25 of 79
구문
MAX(x) OVER (PARTITION BY g) | MIN(x) OVER (ORDER BY d ROWS UNBOUNDED PRECEDING)
엔진 지원
| 엔진 | Support | 메모 |
|---|---|---|
| SQL Server | 예 | Supported under this name. |
| PostgreSQL | 예 | Supported under this name. |
| MySQL | 예 | MySQL 8.0+ |
| SQLite | 예 | SQLite 3.25+ |
| Oracle | 예 | Supported under this name. |
예시
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;
알아 두면 좋은 정보
- 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.
Related on SQLly
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.