Named Windows (WINDOW w AS (...)) for Cleaner Queries
Reuse window definitions with WINDOW aliases to reduce duplication.
In plain words
Write the window once, give it a name, and use the name everywhere you need it.
Think of it like…
Defining a named cell style in a spreadsheet and applying it to many cells: change the style once and every cell using it updates, instead of reformatting each cell by hand.
Where you’ve seen it
A customer order history query computes order number, days since the previous order, running spend and a 3-order moving average: SELECT customer_id, order_id, ROW_NUMBER() OVER w AS n, created_at - LAG(created_at) OVER w AS gap, SUM(amount) OVER (w ROWS UNBOUNDED PRECEDING) AS running_spend, AVG(amount) OVER (w ROWS 2 PRECEDING) AS avg_last_3 FROM orders WINDOW w AS (PARTITION BY customer_id ORDER BY created_at, order_id);
Words you’ll hear
- WINDOW clause
- Defines named windows: WINDOW w AS (PARTITION BY … ORDER BY …).
- OVER w
- Uses the named window exactly as defined, frame included.
- OVER (w …)
- Copies the named window and adds an ORDER BY or a frame.
- Chained windows
- WINDOW a AS (PARTITION BY x), b AS (a ORDER BY y).
Visual diagram
Theory & example queries
Defining and using named windows
Define windows after FROM, WHERE, GROUP BY and HAVING, and before ORDER BY and LIMIT: WINDOW w AS (PARTITION BY dept ORDER BY salary DESC). Several can be defined at once, separated by commas. OVER w uses the window exactly as written. OVER (w ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) copies it and adds a frame, which is how running totals and moving averages share one definition.
Extending follows strict rules in PostgreSQL and the SQL standard: the new window inherits PARTITION BY and can't change it; it can add ORDER BY only if the base window has none; and it can add a frame only if the base window doesn't have one already. So define the base window with partition and order but no frame, and add frames where each function needs them.
SELECT dept, name, salary, AVG(salary) OVER d AS dept_avg, RANK() OVER ds AS dept_rankFROM employeesWINDOW d AS ( PARTITION BY dept ), ds AS ( d ORDER BY salary DESC );PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative employee rankings4 sample rows
| dept | name | salary | dept_avg | dept_rank |
|---|---|---|---|---|
| Engineering | Asha | 125000 | 110000 | 1 |
| Engineering | Ravi | 95000 | 110000 | 2 |
| Sales | Mira | 90000 | 82500 | 1 |
| Sales | Kunal | 75000 | 82500 | 2 |
Note: Sample rows use two employees per department. With tied salaries, RANK may skip the next rank.
Key takeaway: Base window without a frame; add frames per function with OVER (w …).
Support and performance
The WINDOW clause is supported in PostgreSQL, MySQL 8.0+, SQLite, SQL Server 2022+, Oracle 21c+ and BigQuery, among others. In engines without it, you must repeat the OVER (…) text, so portable code sometimes avoids it.
Naming a window doesn't change performance by itself: the planner already shares one sort among window functions with identical partition and order. What it does is make sharing visible. If two functions need different ORDER BYs, the database needs two sorts, and seeing two different named windows makes that cost obvious in review.
| day | amount |
|---|---|
| 2026-11-15 | 100 |
| 2026-11-17 | 200 |
| 2026-11-21 | 50 |
| 2026-11-22 | 75 |
SELECT DAY, revenue, AVG(revenue) OVER (w ROWS 6 PRECEDING) AS ma_7, AVG(revenue) OVER (w ROWS 27 PRECEDING) AS ma_28FROM daily_revenueWINDOW w AS ( ORDER BY DAY );PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative partial windows4 sample rows
| day | revenue | ma_7 | ma_28 |
|---|---|---|---|
| 2026-11-01 | 100 | 100 | 100 |
| 2026-11-02 | 200 | 150 | 150 |
| 2026-11-03 | 50 | 116.67 | 116.67 |
| 2026-11-04 | 150 | 125 | 125 |
Note: The sample starts at the beginning of the series, so both frames contain the same currently available rows. Exact averages can differ once 7 or 28 complete rows exist.
Key takeaway: Widely supported; same definitions share one sort either way.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Spot repeated OVER clauses
Find window functions that repeat the same PARTITION BY and ORDER BY.
OVER (PARTITION BY customer_idORDER BY created_at) × 4When to use it & trade-offs
What it is
The WINDOW clause lets you define a window once, give it a name, and use it in many window functions: … OVER w … WINDOW w AS (PARTITION BY customer_id ORDER BY created_at). A named window can also be extended, as in OVER (w ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), and one named window can build on another. It goes after HAVING and before ORDER BY.
Why it matters: Analytical queries often apply five or six window functions over the same partition and order: row number, previous value, running total, moving average. Repeating the full OVER (…) each time is noisy, and when someone changes the ORDER BY in one copy but not the others, the results become subtly inconsistent. Named windows fix both problems.
When to reach for it
- Order-history and event-sequence analysis
- Several moving averages over the same series
- Rankings and comparisons within the same groups
When to avoid or be careful
- Putting a frame in the base window you plan to extend
- Trying to change PARTITION BY when extending a window
- Using WINDOW in SQL that must run on engines without it
Named windows vs repeated OVER clauses
Strengths: Defined once; consistent; easier to change and review.
Watch out: Not supported in every engine; extension rules to learn.
Strengths: Works everywhere; self-contained.
Watch out: Copies can drift apart; noisy.
Strengths: Each value computed once and named.
Watch out: Doesn't remove repeated window definitions inside the CTE.
Interview signals & numbers to know
When this topic comes up
- “Clean up this query with six window functions”
- “Running total and moving average together”
- Repeated OVER clauses
- Query readability
- Window function syntax
Benchmarks & rules of thumb
- after HAVING
- where the WINDOW clause goes
- SQL Server 2022
- first version with the WINDOW clause
- MySQL 8.0
- WINDOW clause support
Common mistakes & follow-ups
Common interview mistakes
- Defining WINDOW w AS (… ROWS UNBOUNDED PRECEDING) and then writing OVER (w ROWS 2 PRECEDING), which is an error.
- Placing the WINDOW clause after ORDER BY.
- Writing OVER (w PARTITION BY region) to change the partition, which isn't allowed.
Likely interviewer follow-ups
- How would you simplify a query that repeats the same OVER clause five times?
- Can you add a frame to a named window? What are the rules?
- Does a named window make a query faster?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Named Windows (WINDOW w AS (...)) for Cleaner Queries with hands-on SQL practice and interview Q&A.