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
function() OVER (
PARTITION BY column -- optional: restart for each group
ORDER BY column -- optional: order within the window
)Group totals next to each row
Compare with GROUP BY, which would give one row per category instead of one per product.
Ranking
| 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".
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.
LAG and LEAD: previous and next rows
Moving averages with frames
A frame limits which rows the window looks at.
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.
1.How do window functions differ from GROUP BY?
2.Prices 50, 50, 40 ranked by DENSE_RANK() descending give…