Mastering SQL Window Functions
Window functions are the single highest-leverage SQL skill for analytics. Here is a practical, example-driven guide.
Why window functions matter
Window functions let you compute across a set of rows related to the current row without collapsing them into a group. That means running totals, rankings, and period-over-period math in a single, readable query.
Callout: If you find yourself self-joining a table to itself to compare rows, a window function is almost always the better tool.
A running total
select
order_date,
revenue,
sum(revenue) over (
order by order_date
rows between unbounded preceding and current row
) as running_revenue
from daily_sales
order by order_date;Ranking within groups
select
category,
product,
revenue,
row_number() over (partition by category order by revenue desc) as rank_in_category
from product_sales;| Function | Use case |
|---|---|
row_number() | Unique ordering / de-duplication |
rank() | Ranking with gaps on ties |
lag() / lead() | Period-over-period comparison |
The mental model
Master the frame clause and the rest follows.
Enjoyed this post?
Get new analytics tutorials in your inbox.
Related articles
A Practical Intro to Analytics Engineering with dbt
dbt brought software engineering discipline to SQL. Here is how staging, marts, tests, and docs fit together.
Five DAX Patterns Every Power BI Analyst Should Know
Time intelligence, running totals, and the golden rule of measures vs. calculated columns.
Breaking Into Analytics Engineering in 2025
The skills, portfolio, and interview prep that actually move the needle for analytics roles.