Sub topic 13
Reusing definitions with the WINDOW clause
This chapter assumes you can already write OVER (PARTITION BY ... ORDER BY ...) and know what a frame is. The WINDOW clause lets you name a window definition once and refer to it from several functions in the same query. It changes how the query reads and how easy it is to maintain. It does not change what the functions compute.
The problem: repeated definitions
Queries with several window functions often repeat the same definition:
SELECT
region,
sale_date,
amount,
SUM(amount) OVER (PARTITION BY region ORDER BY sale_date, id ROWS UNBOUNDED PRECEDING) AS running_total,
AVG(amount) OVER (PARTITION BY region ORDER BY sale_date, id ROWS UNBOUNDED PRECEDING) AS running_avg,
COUNT(*) OVER (PARTITION BY region ORDER BY sale_date, id ROWS UNBOUNDED PRECEDING) AS running_count
FROM sales;The three definitions are identical. If you later change the ordering, you must edit every copy. If you miss one, that column quietly uses a different window and the result looks plausible but is wrong.
Naming a window
Declare the definition once in a WINDOW clause, then refer to it by name after OVER:
SELECT
region,
sale_date,
amount,
SUM(amount) OVER w AS running_total,
AVG(amount) OVER w AS running_avg,
COUNT(*) OVER w AS running_count
FROM sales
WINDOW w AS (
PARTITION BY region
ORDER BY sale_date, id
ROWS UNBOUNDED PRECEDING
);The general form is:
WINDOW window_name AS (window_definition) [, window_name AS (window_definition) ...]The window definition inside the parentheses is the same as the one you would put inside OVER (...). It can contain PARTITION BY, ORDER BY and a frame clause, and each part is optional.
Where the clause goes
WINDOW sits after HAVING and before the final ORDER BY:
SELECTFROMWHEREGROUP BYHAVINGWINDOWORDER BYLIMIT
Writing it after the final ORDER BY is a syntax error. This is a common slip when you add the clause to an existing query.
Sample data
The examples below use this table. The statements run on PostgreSQL, MySQL 8+ and SQLite 3.25+.
CREATE TABLE sales (
id INTEGER PRIMARY KEY,
region VARCHAR(20),
sale_date DATE,
amount NUMERIC(10, 2)
);
INSERT INTO sales (id, region, sale_date, amount) VALUES
(1, 'North', '2026-01-05', 100),
(2, 'North', '2026-01-12', 250),
(3, 'North', '2026-01-20', 150),
(4, 'South', '2026-01-07', 300),
(5, 'South', '2026-01-15', 200),
(6, 'South', '2026-01-28', 100);Building one window on another
A named window can serve as the base for another window. The new definition starts from the base and adds to it. This is useful when two functions share a partition but need different ordering or frames.
SELECT
id,
region,
amount,
SUM(amount) OVER w AS region_total,
SUM(amount) OVER (w ORDER BY sale_date, id) AS running_total
FROM sales
WINDOW w AS (PARTITION BY region)
ORDER BY region, sale_date, id;The window w only partitions, so SUM(amount) OVER w totals the whole partition. The second function writes (w ORDER BY sale_date, id). That copies the partitioning from w and adds an ordering, which makes the sum cumulative.
| id | region | amount | region_total | running_total |
|---|---|---|---|---|
| 1 | North | 100 | 500 | 100 |
| 2 | North | 250 | 500 | 350 |
| 3 | North | 150 | 500 | 500 |
| 4 | South | 300 | 600 | 300 |
| 5 | South | 200 | 600 | 500 |
| 6 | South | 100 | 600 | 600 |
You can also chain definitions inside the WINDOW clause. A later entry can refer to an earlier one:
SELECT
id,
region,
sale_date,
amount,
LAG(amount) OVER by_date AS prev_amount,
SUM(amount) OVER by_date AS running_total,
AVG(amount) OVER (by_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg_3
FROM sales
WINDOW
by_region AS (PARTITION BY region),
by_date AS (by_region ORDER BY sale_date, id)
ORDER BY region, sale_date, id;Here by_region holds the partition, and by_date adds the ordering. The third function takes by_date and adds a frame. Every function shares one partitioning rule, so the partitioning is written in exactly one place.
Rules for extending a window
When a definition starts with an existing window name, three rules apply. PostgreSQL documents them, and MySQL and SQLite follow the same standard rules.
- No second PARTITION BY. The new window inherits the partitioning and cannot specify its own.
- ORDER BY only if the base has none. You can add an ordering to a base that lacks one. You cannot replace or override an existing ordering.
- The base must not have a frame clause. The new window supplies its own frame, so a base that already specifies one is not allowed.
Each rule has a practical consequence:
- Put only the parts that all users share into the base. That is usually just the
PARTITION BY, sometimes with theORDER BY. - Leave the frame out of a window you plan to extend.
- If two functions need different orderings over the same partition, base both on a partition-only window.
This fails because the base already has an ORDER BY:
SELECT
SUM(amount) OVER (w ORDER BY amount DESC) AS bad
FROM sales
WINDOW w AS (PARTITION BY region ORDER BY sale_date);The database rejects it with an error about overriding the ORDER BY of window w. The exact wording varies by system.
OVER w versus OVER (w)
OVER w uses the named window exactly as defined. OVER (w) copies it and allows additions, as in OVER (w ORDER BY ...). With nothing added the two look the same. The standard treats them differently, though, because the parenthesised form is a new window built from a copy. One consequence is that a base window with a frame clause works as OVER w but cannot be extended with OVER (w ...). When you want a fully specified window, write OVER w. When you want to extend one, write OVER (w ...).
What naming does not do
The WINDOW clause is a syntax feature. A named window is not computed once and cached, and it does not make the query faster by itself. Two things matter for performance:
- Functions whose windows have the same partitioning and ordering can often be evaluated in a single sorted pass. Whether you write that definition once or three times, the database should see equivalent windows. Check this with
EXPLAINon your system. - Functions with different
PARTITION BYorORDER BYneed separate sorts. Naming them does not remove that cost.
Treat the clause as a readability and maintenance tool. Reasons to use it:
- Two or more functions in one query share all or part of a definition.
- You want the window logic stated once, near the end of the query, so the
SELECTlist stays short. - You are extending a shared partition with different orderings or frames, as in the chained example.
Reasons to skip it:
- Only one window function appears in the query. A name adds indirection and nothing else.
- Each function has a different window. Naming them gains nothing.
- The query must run on a system without support (see below).
Dialect support
| System | `WINDOW` clause |
|---|---|
| PostgreSQL | Supported |
| MySQL 8.0+ | Supported |
| SQLite 3.25+ | Supported |
| SQL Server | Not supported before SQL Server 2022. Newer versions add it at database compatibility level 160. Check your version. |
| Oracle | Check the documentation for your release. Many versions need the definition repeated inline. |
If you must support a system without the clause, repeat the definition inline. Alternatively, generate the repeated OVER (...) text from application code or a template so it stays consistent.
Common mistakes
- Putting
WINDOWin the wrong place. It goes before the finalORDER BY, not after. - Referring to an undefined name. A typo in
OVER wndproduces an error that the window does not exist. - Trying to override. Adding
PARTITION BYto a derived window, or a secondORDER BY, is an error. - Basing a window on one with a frame. Keep frames out of bases.
- Assuming a name implies reuse of results. Each function still computes its own value over the window.
Exercise
Rewrite this query with a WINDOW clause so that the partitioning is written once, while the two functions keep different orderings. Then explain why you cannot put the ORDER BY in the base window. SELECT id, SUM(amount) OVER (PARTITION BY region ORDER BY saledate, id) AS bydatetotal, SUM(amount) OVER (PARTITION BY region ORDER BY amount DESC, id) AS byamount_total FROM sales;
Show answer
SELECT id, SUM(amount) OVER (w ORDER BY saledate, id) AS bydatetotal, SUM(amount) OVER (w ORDER BY amount DESC, id) AS byamount_total FROM sales WINDOW w AS (PARTITION BY region); The base window w holds only the partition. A derived window may add an ORDER BY only if the base has none, and it cannot override an existing one. If w included an ORDER BY, neither function could supply its own ordering.
Exercise
A colleague writes WINDOW w AS (PARTITION BY region ORDER BY sale_date, id ROWS UNBOUNDED PRECEDING) and then uses OVER (w ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) for a moving average. Why does this fail, and how would you restructure the definitions?
Show answer
The base window w already has a frame clause, and a window that extends another must have a base without a frame. Split the definitions: WINDOW bydate AS (PARTITION BY region ORDER BY saledate, id). Then use OVER (bydate ROWS UNBOUNDED PRECEDING) for the running total and OVER (bydate ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) for the moving average.