Window functions let you run aggregate-like calculations across related rows without collapsing them into a single result.
Window functions return an aggregated value (sum, rank, moving average) for each row while keeping every row visible. They avoid self-joins and subqueries, making analytical queries shorter and faster.
Place the function in the SELECT list followed by OVER()
.Inside the parentheses you optionally define PARTITION BY
, ORDER BY
, frame clauses such as ROWS BETWEEN
, or attach a named WINDOW
.
PARTITION BY
?Use PARTITION BY
when you need independent calculations per logical group, such as per customer or per order. Omitting it runs the calculation over the entire result set.
ROWS
and RANGE
frames?ROWS
counts physical rows before/after the current one, perfect for running totals.RANGE
uses value ranges in the ORDER BY
column, helpful for date buckets or price bands.
Order the rows by order_date
and apply SUM(total_amount) OVER (PARTITION BY customer_id ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
.
Yes.Each function can use its own window clause, or they can share a named window defined in the WINDOW
clause at the end of the query.
Define complex partitions once in a WINDOW w AS (...)
clause, then refer to OVER w
for every function. This keeps queries readable and reduces duplication.
MariaDB materializes the window once per partition.Add appropriate indexes on PARTITION BY
and ORDER BY
columns to avoid full table scans.
.
Not necessarily. They avoid extra joins and let MariaDB process each partition once. With proper indexes, they can be comparable or faster.
No. In MariaDB 10.5+, window functions are only allowed in SELECT clauses. Use a subquery to compute the windowed value, then join in an UPDATE.
Window functions became available in MariaDB 10.2.0 (stable in 10.2.2). Upgrade if you run an older release.