Anatomy of OVER() Clause (PARTITION BY, ORDER BY, Window Frame)
Break down PARTITION BY, ORDER BY, and frame clauses inside OVER().
In plain words
OVER tells a window function which rows to look at: which group, in what order, and how many rows around the current one.
Think of it like…
A teacher marking exams: PARTITION BY is "separately for each class", ORDER BY is "in order of roll number", and the frame is "compare each student with the three before them". OVER () with nothing inside is "compare with the whole school".
Where you’ve seen it
SELECT name, dept, salary, AVG(salary) OVER (PARTITION BY dept) AS dept_avg, RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS dept_rank, SUM(salary) OVER () AS payroll FROM employees; gives each employee their department average, their rank within the department and the company payroll, all in one pass.
Words you’ll hear
- PARTITION BY
- Splits rows into groups; the function restarts for each group.
- ORDER BY (in OVER)
- Orders rows within each partition; required for ranking and LAG/LEAD.
- Frame
- The rows around the current row that aggregate functions use.
- OVER ()
- One window containing every row of the result.
Visual diagram
Theory & example queries
PARTITION BY and ORDER BY
PARTITION BY works like GROUP BY without collapsing rows: each row is computed only against rows in the same partition. Leave it out and every row sees the whole result set. You can partition by several columns or expressions, such as PARTITION BY customer_id, date_trunc('month', created_at).
ORDER BY inside OVER decides the sequence within each partition. Ranking functions and LAG/LEAD need it. For aggregates, adding ORDER BY changes the meaning: SUM(x) OVER (PARTITION BY g) is the group total on every row, while SUM(x) OVER (PARTITION BY g ORDER BY d) is a running total, because ORDER BY switches the default frame to "start of partition up to the current row". It doesn't sort the query's output; add a normal ORDER BY at the end for that.
SELECT DAY, amount, SUM(amount) OVER () AS total, SUM(amount) OVER ( ORDER BY DAY ) AS runningFROM daily_salesORDER BY DAY;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Grand total versus running total3 sample rows
| day | amount | total | running |
|---|---|---|---|
| 2026-11-01 | 100 | 450 | 100 |
| 2026-11-02 | 200 | 450 | 300 |
| 2026-11-03 | 150 | 450 | 450 |
Note: Sample data totals 450 across three days and has no tied dates. With tied ORDER BY values, the default RANGE frame gives peers the same running value.
Key takeaway: PARTITION BY picks the group; ORDER BY sets the sequence and turns aggregates into running ones.
Frames, evaluation order and reuse
The frame (ROWS BETWEEN 6 PRECEDING AND CURRENT ROW, RANGE …, GROUPS …) narrows what aggregate and value functions see. Ranking functions and LAG/LEAD ignore it. Write the frame explicitly whenever ORDER BY is present, so ties and LAST_VALUE behave predictably.
Window functions are computed after WHERE, GROUP BY and HAVING, and before the final ORDER BY and LIMIT, so you can't filter on them in the same WHERE; wrap the query and filter outside. When several functions share a window, name it once with the WINDOW clause: … OVER w … WINDOW w AS (PARTITION BY dept ORDER BY salary DESC).
SELECT name, RANK() OVER w AS rnk, salary - LAG(salary) OVER w AS gapFROM employeesWINDOW w AS ( PARTITION BY dept ORDER BY salary DESC );PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative salary gaps3 sample rows
| name | rnk | gap |
|---|---|---|
| Asha | 1 | NULL |
| Ravi | 2 | -30000 |
| Mira | 3 | -15000 |
Note: These sample employees are in one department, with salaries 125000, 95000 and 80000. The first row has no previous row, so LAG and therefore gap are NULL.
Key takeaway: Frames shape aggregates; windows run after WHERE; WINDOW names repeated definitions.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Choose the groups
Decide whether each row should be compared with its own group (department, customer) or with everything.
PARTITION BY deptWhen to use it & trade-offs
What it is
The OVER() clause turns a function into a window function and defines which rows it looks at for each row. It has three optional parts: PARTITION BY splits rows into independent groups, ORDER BY sets the order inside each group, and the frame (ROWS / RANGE …) chooses a slice around the current row. OVER () with nothing inside means "all rows of the result".
Why it matters: Every window function (ranking, running totals, LAG, moving averages) is configured through OVER. Most window bugs come from one of its three parts: a missing PARTITION BY, an ORDER BY that silently changes the default frame, or a frame that isn't what you assumed.
When to reach for it
- Group context on detail rows
- Rankings and comparisons with neighbouring rows
- Running and moving aggregates
When to avoid or be careful
- Adding ORDER BY to an aggregate window when you wanted the group total
- Assuming OVER's ORDER BY sorts the final output
- Repeating long window definitions instead of using WINDOW
OVER() variations
Strengths: Simplest window: the whole result.
Watch out: No per-group context.
Strengths: Group context without collapsing rows.
Watch out: Adding ORDER BY changes it into a running calculation.
Strengths: Full control of sequence and slice.
Watch out: Easy to get the frame or ties wrong.
Interview signals & numbers to know
When this topic comes up
- “What does PARTITION BY do?”
- “Why is my SUM OVER a running total?”
- Window functions in general
- OVER () vs OVER (PARTITION BY)
- Named windows
Benchmarks & rules of thumb
- 3
- optional parts: PARTITION BY, ORDER BY, frame
- OVER ()
- the whole result as one window
- After WHERE
- when window functions are computed
Common mistakes & follow-ups
Common interview mistakes
- Writing SUM(amount) OVER (PARTITION BY customer_id ORDER BY created_at) to get the customer total, and getting running totals instead.
- Forgetting PARTITION BY, so a ranking runs across all customers instead of within each.
- Relying on OVER's ORDER BY to order the result rows.
Likely interviewer follow-ups
- What's the difference between SUM(x) OVER (PARTITION BY g) and SUM(x) OVER (PARTITION BY g ORDER BY d)?
- Can you use a window function in WHERE? Why not?
- How do you reuse the same window definition for several functions?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Anatomy of OVER() Clause (PARTITION BY, ORDER BY, Window Frame) with hands-on SQL practice and interview Q&A.