Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SQL
SQL
0/12 completed
Beginner
What is a database?SELECT: reading dataFiltering with WHERESorting and limiting results
Intermediate
Aggregates and GROUP BYJOINs: combining tablesINSERT, UPDATE and DELETECreating tables and constraints
Advanced
Subqueries and CTEsWindow functions
Pro
Indexes and transactionsDatabase design and normalization
Tracks / SQL / Advanced

Window functions

GROUP BY collapses rows into one per group. Window functions calculate across a group of rows without collapsing them. You keep every row and get the group calculation next to it. They're used for rankings, running totals, "previous value" comparisons and top-N-per-group queries.

The syntax

sql
function() OVER (
  PARTITION BY column   -- optional: restart for each group
  ORDER BY column       -- optional: order within the window
)

Group totals next to each row

SQL · editable

Compare with GROUP BY, which would give one row per category instead of one per product.

Ranking

SQL · editable
Function Ties get… Example for prices 10, 10, 8
ROW_NUMBER() different numbers 1, 2, 3
RANK() same number, then a gap 1, 1, 3
DENSE_RANK() same number, no gap 1, 1, 2

Top N per group

A very common interview and real-world question: "the most expensive product in each category".

SQL · editable

You can't put a window function in WHERE (it's evaluated after WHERE), so wrap it in a CTE first.

Running totals

With ORDER BY inside OVER, aggregates become cumulative.

SQL · editable

LAG and LEAD: previous and next rows

SQL · editable

Moving averages with frames

A frame limits which rows the window looks at.

SQL · editable

Practice

For each customer, list their orders with an order_number (1 = their first order) and the number of days since their previous order. Hint: ROW_NUMBER(), LAG(), and julianday(a) - julianday(b) for date differences in SQLite.

SQL · editable
✎ Check your understanding

1.How do window functions differ from GROUP BY?

2.Prices 50, 50, 40 ranked by DENSE_RANK() descending give…

← Subqueries and CTEs