SQL Data Analytics • Lesson 18

Advanced Window Functions

Go beyond ROW_NUMBER() with RANK(), DENSE_RANK(), LAG() and LEAD() for deeper analytical comparisons.

Your progress0%

0 of 8 concepts completed

Complete the activity and related MCQ to unlock the next concept.

Concept 1RANK

RANK() Handles Ties with Gaps

RANK() gives tied values the same rank and leaves gaps afterward. If two rows tie at rank 2, the next row receives rank 4 — not 3.

Interactive Data

Sales table

Six sales with deliberate ties at ₹27,000 and ₹18,000 — the ties are what make RANK, DENSE_RANK and ROW_NUMBER visibly different.

6
ROWS
2
CITIES
2
TIES
idsalespersoncityamountrow_numberrankdense_rank
1RahulDelhi₹32,000111
2AmitDelhi₹27,000222
3ArjunDelhi₹27,000322
4PriyaMumbai₹21,000443
5KavyaMumbai₹18,000554
6NehaMumbai₹18,000654

LAG / LEAD view

idsalespersonamountpreviousnextchange
1Rahul₹32,000—₹27,000—
2Amit₹27,000₹32,000₹27,000₹-5,000
3Arjun₹27,000₹27,000₹21,000₹0
4Priya₹21,000₹27,000₹18,000₹-6,000
5Kavya₹18,000₹21,000₹18,000₹-3,000
6Neha₹18,000₹18,000—₹0

Learn by Seeing

Ties share a rank, gaps appear

RANK() OVER (
  ORDER BY amount DESC
)

Amit and Arjun both have ₹27,000 — they share rank 2, and the next row starts at 4.

RANK — ties share a rank, gaps appear afterwards

Rahul · ₹32,000rank 1
Amit · ₹27,000rank 2
Arjun · ₹27,000rank 2
Priya · ₹21,000rank 4
Kavya · ₹18,000rank 5
Neha · ₹18,000rank 5

Rank 3 is skipped because Amit and Arjun share rank 2 — the next number jumps to 4.

Interactive Activity

How many salespeople share the same rank in this dataset?

Hint: Look for pairs of equal amounts: 27000 twice and 18000 twice.

SQL Analyst Mindset

Compare, rank and look sideways

Real analytics rarely stops at "how much". It asks "how does this compare to the previous row?", "who is the top performer in this group?", "how many rows share this rank?". Advanced window functions answer those questions in a single pass.

01

Rank

RANK vs DENSE_RANK vs ROW_NUMBER.

02

Group

PARTITION BY city or region.

03

Look back

LAG for the previous row.

04

Look ahead

LEAD for the next row.

Frequently Asked Questions

Advanced Window Functions — FAQs

When should I use RANK vs DENSE_RANK?

Use RANK when gaps are acceptable (e.g. sports standings). Use DENSE_RANK when you want continuous numbers even with ties.

What does LAG return on the first row?

NULL — there is no previous row. You can supply a default via LAG(column, 1, default_value).

Does LAG / LEAD require a sorted window?

Yes. Without ORDER BY inside OVER(), the previous / next row is undefined.

Can I use PARTITION BY with LAG and LEAD?

Absolutely. PARTITION BY city with LAG(amount) gives you the previous sale within each city, not across the whole table.

Lesson Summary

What you learned

RANK()

Ties share a rank; gaps appear after the tie.

DENSE_RANK()

Ties share a rank with no gaps.

LAG()

Access the previous row's value.

LEAD()

Access the next row's value.