SQL Data Analytics • Lesson 17

Window Functions — Basics

Learn how SQL calculates rankings, row numbers and partition-based analysis without collapsing your original rows.

Your progress0%

0 of 8 concepts completed

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

Concept 1WHY WINDOW

The Big Idea Behind Windows

A window function calculates across related rows but keeps every original row in the result. Unlike GROUP BY, which collapses rows into groups, window functions preserve the detail you are analyzing.

Interactive Data

Sales table

Six individual sales — the raw detail that window functions operate on without collapsing.

6
SALES
2
CITIES
₹32,000
TOP SALE
idsalespersoncityamountrow_number (desc)city_rank
3AmitDelhi₹32,00011
5ArjunDelhi₹27,00022
1RahulDelhi₹25,00033
6KavyaMumbai₹21,00041
2PriyaMumbai₹18,00052
4NehaMumbai₹15,00063

Learn by Seeing

GROUP BY vs window

GROUP BY  → collapses rows into groups
OVER()    → keeps rows, adds a calculation

GROUP BY reduces rows. Window functions add analytical columns without removing any row.

GROUP BY vs window — toggle to compare

Rows returned

2 (one per city)

GROUP BY collapses rows into one per group.

Interactive Activity

What does a window function allow you to do?

Hint: Compare it to GROUP BY, which removes the detail.

SQL Analyst Mindset

Add insight without losing detail

Aggregation compresses rows. Window functions enrich them. When the business wants "the top performer in each region" or "the rank of each sale", window functions return the answer without losing the underlying transaction detail.

01

Define window

OVER() plus optional PARTITION BY.

02

Order rows

ORDER BY controls ranking.

03

Apply function

ROW_NUMBER, RANK, SUM, ...

04

Keep rows

Every detail row stays in the result.

Frequently Asked Questions

Window Functions — FAQs

How is OVER() different from GROUP BY?

GROUP BY collapses rows into one row per group. OVER() keeps every row and adds a computed column alongside it.

Can I use WHERE on a window function?

No. Window functions run after WHERE. Wrap the query in a CTE or subquery if you need to filter on the window result.

What is the difference between ROW_NUMBER and RANK?

ROW_NUMBER gives every row a unique number (ties get different numbers). RANK gives equal values the same rank and skips the next numbers.

Does PARTITION BY sort the result?

No. PARTITION BY groups rows for the window calculation but does not change the final row order — use a top-level ORDER BY for that.

Lesson Summary

What you learned

OVER()

Defines the window a function operates across.

ROW_NUMBER()

Assigns a unique sequential number per row.

ORDER BY inside OVER

Controls ranking direction.

PARTITION BY

Restarts the window per group, enabling per-group ranking.