Interview Q&A / SQL & DBMS

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What do PARTITION BY and ORDER BY do inside OVER()?

SHORT ANSWER

PARTITION BY splits rows into independent groups, and ORDER BY sorts rows within each group. For aggregates, adding ORDER BY also turns the result into a running calculation.

Explain it simply

PARTITION BY is like separating exam papers into piles by section. ORDER BY then sorts the papers inside each pile by marks. The window function works pile by pile and never looks across piles.

Example

Table sales(city, day, amount): Pune has 100 on day 1 and 50 on day 2; Delhi has 70 on day 1.

sql
SELECT city, day, amount,
       SUM(amount) OVER (PARTITION BY city)               AS city_total,
       SUM(amount) OVER (PARTITION BY city ORDER BY day)  AS running
FROM sales;
citydayamountcity_totalrunning
Delhi1707070
Pune1100150100
Pune250150150
  • Without ORDER BY, SUM covers the whole partition, so every Pune row shows 150.
  • With ORDER BY, the default frame runs from the first row to the current row, giving a running total.
  • With no PARTITION BY, the whole result is one partition.

What to say in the interview

"PARTITION BY defines the groups, ORDER BY defines the sequence within each group. Ranking functions need ORDER BY. For aggregates, ORDER BY makes them cumulative."

Common mistakes

  • Forgetting that ORDER BY inside OVER changes an aggregate from a total to a running total.

#sql#window-functions#partition-by

Related questions

Practise more SQL & DBMS questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open SQL & DBMS quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.