Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 82/ 160
05. Window Functions & Analytical SQL

Anatomy of OVER() Clause (PARTITION BY, ORDER BY, Window Frame)

Break down PARTITION BY, ORDER BY, and frame clauses inside OVER().

BeginnerPARTITION BY · ORDER BY3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Same function, two meaningsQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  DAY,3  amount,4  SUM(amount) OVER () AS total,5  SUM(amount) OVER (6    ORDER BY7      DAY8  ) AS running9FROM10  daily_sales11ORDER BY12  DAY;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/12
3OutputInspect the representative rows, affected-row count, plan, or command status.
Grand total versus running total3 sample rows
Grand total versus running total
dayamounttotalrunning
2026-11-01100450100
2026-11-02200450300
2026-11-03150450450

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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).

A named windowQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  name,3  RANK() OVER w AS rnk,4  salary - LAG(salary) OVER w AS gap5FROM6  employees7WINDOW8  w AS (9    PARTITION BY10      dept11    ORDER BY12      salary DESC13  );
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/13
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative salary gaps3 sample rows
Representative salary gaps
namernkgap
Asha1NULL
Ravi2-30000
Mira3-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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Frames shape aggregates; windows run after WHERE; WINDOW names repeated definitions.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1PARTITION BY

Choose the groups

Decide whether each row should be compared with its own group (department, customer) or with everything.

SQL at this step
1PARTITION BY2  dept
What to watch at this step
Omit
for whole result
Tip: use ← → to move between steps

When 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

OVER ()
Best for: Grand totals and overall shares on every row

Strengths: Simplest window: the whole result.

Watch out: No per-group context.

OVER (PARTITION BY …)
Best for: Group totals and averages next to detail rows

Strengths: Group context without collapsing rows.

Watch out: Adding ORDER BY changes it into a running calculation.

OVER (PARTITION BY … ORDER BY … frame)
Best for: Rankings, running totals, moving averages, LAG/LEAD

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?
Interview tip: Explain OVER as three dials (group, order, frame), then show the SUM OVER with and without ORDER BY. That one comparison clears up most window confusion.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Window Functions vs GROUP BY Aggregations (Preserving Row Granularity)
Next topic
Ranking Functions: ROW_NUMBER(), RANK(), DENSE_RANK()