⚡0 XP🔥0

Window Functions (Ranking, Running Totals, LAG/LEAD)

Lesson 7 of 8 ⏱ 5 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs SQL

Calculate across related rows without collapsing them - ROW_NUMBER, RANK, DENSE_RANK, PARTITION BY, running totals, moving averages, percentage of total, and month-on-month change with LAG and LEAD.

What are window functions?#

A window function performs a calculation across a set of rows related to the current row - without collapsing them into one row like GROUP BY does.

function_name(...) OVER (
    PARTITION BY column     -- optional: restart for each group
    ORDER BY column         -- optional: order within the window
)
▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

Every product row is kept, and each gets its category's average next to it - impossible with a simple GROUP BY.

हिंदी में समझें

Window function = हर row के साथ उसके "आस-पास के समूह" (window) की calculation जोड़ना - rows को मिलाए बिना।

GROUP BY में हर category की एक row बचती है। Window function में सारी rows रहती हैं और हर row के आगे उसकी category का औसत, rank, running total आदि लिख दिया जाता है।

  • PARTITION BY = किस समूह में calculation करनी है (हर category अलग)
  • ORDER BY (OVER के अंदर) = rank या running total किस क्रम में

Ranking functions#

Function Ties (100, 90, 90, 80) Use
ROW_NUMBER() 1, 2, 3, 4 unique numbering, "pick one per group"
RANK() 1, 2, 2, 4 competition ranking (gaps after ties)
DENSE_RANK() 1, 2, 2, 3 ranking without gaps
NTILE(4) quartile 1-4 split into equal buckets
▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

Top N per group#

Window functions can't go directly in WHERE - compute them in a CTE first:

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

Aggregate window functions#

SUM, AVG, COUNT, MIN, MAX all work with OVER.

Percentage of total#

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

OVER () with nothing inside = the window is all rows of the result.

Running total#

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

Moving average#

A frame clause limits the window to nearby rows:

AVG(revenue) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)   -- 3-month moving average

LAG and LEAD - comparing with previous/next rows#

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run
  • LAG(col, n, default) - value n rows before (default n = 1).
  • LEAD(col, n, default) - value n rows after.
  • Month-on-month growth % = (x - LAG(x)) * 100.0 / LAG(x).

Customer behaviour: days between orders#

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

Window functions cheat sheet#

Question Window function
Rank products by sales RANK() OVER (ORDER BY sales DESC)
Top 3 per region ROW_NUMBER() OVER (PARTITION BY region ORDER BY sales DESC) + filter
% of total x * 100.0 / SUM(x) OVER ()
% within group x * 100.0 / SUM(x) OVER (PARTITION BY group)
Running total SUM(x) OVER (ORDER BY date)
Moving average AVG(x) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
Month-on-month change x - LAG(x) OVER (ORDER BY month)
First purchase date per customer MIN(order_date) OVER (PARTITION BY customer_id)

Summary#

  • Window functions calculate across related rows and keep every row: f() OVER (PARTITION BY ... ORDER BY ...).
  • Ranking: ROW_NUMBER, RANK, DENSE_RANK, NTILE; filter top-N in a CTE.
  • Aggregates over windows give % of total, running totals and moving averages.
  • LAG and LEAD compare a row with previous/next rows - growth, gaps, trends.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Rank products by price

Show name, price and price_rank - the product's rank by price, most expensive = 1, using RANK(). Sort by price_rank.

Database: shop (see the tables in this lesson)
2

Most expensive product per category

Show the single most expensive product in each category - columns category, name, price. Sort by category.

Database: shop (see the tables in this lesson)
3

Running count of orders in 2025

For each month of 2025 show month (YYYY-MM), orders (number of orders that month) and running_total (cumulative orders so far in 2025). Sort by month.

Database: shop (see the tables in this lesson)

Quick Quiz

Q1.

How is a window function different from GROUP BY?

Q2.

Prices 100, 90, 90, 80 ranked highest first - what does RANK() give?

Q3.

What does PARTITION BY category do?

Q4.

Which function returns the previous row's value?

Q5.

How do you get the top 2 products in EACH category?