SQL Window Functions: A Gentle Guide

SQL Window Functions: A Gentle Guide – DataScienceWay tutorial

Window functions are where SQL goes from useful to powerful. They let you calculate running totals, rankings, moving averages and comparisons with the previous row – all while keeping every original row in the result. Tasks that once needed awkward self-joins or exporting to Excel become a single, readable query.

This guide explains how window functions differ from GROUP BY, then works through PARTITION BY, ORDER BY, ranking functions, LAG and LEAD, running totals, moving averages and frames. Everything runs in SQLite 3.25 or later (any recent Python includes a suitable version) and works in PostgreSQL, SQL Server, MySQL 8+ and cloud warehouses with little or no change.

Sample data

CREATE TABLE monthly_sales (
    region   TEXT,
    month    TEXT,
    revenue  REAL
);
INSERT INTO monthly_sales VALUES
 ('North', '2024-01', 100), ('North', '2024-02', 120), ('North', '2024-03', 90),
 ('North', '2024-04', 150), ('South', '2024-01', 200), ('South', '2024-02', 180),
 ('South', '2024-03', 210), ('South', '2024-04', 260), ('East',  '2024-01', 80),
 ('East',  '2024-02', 80),  ('East',  '2024-03', 95),  ('East',  '2024-04', 110);

Step 1: GROUP BY versus a window

GROUP BY collapses rows: one output row per region. A window function calculates across a set of rows but returns a value for every row:

-- GROUP BY: 3 rows
SELECT region, SUM(revenue) AS region_total
FROM monthly_sales
GROUP BY region;

-- Window: all 12 rows, each with its region total alongside
SELECT region, month, revenue,
       SUM(revenue) OVER (PARTITION BY region) AS region_total
FROM monthly_sales
ORDER BY region, month;

The OVER (...) clause is what makes a function a window function. Inside it:

  • PARTITION BY splits rows into groups (like GROUP BY, but without collapsing them).
  • ORDER BY sets the order of rows within each partition, which matters for rankings, running totals and LAG/LEAD.

An empty OVER () treats the whole result as one window.

Step 2: Percentage of total

With the total on every row, shares are simple:

SELECT region, month, revenue,
       ROUND(100.0 * revenue / SUM(revenue) OVER (PARTITION BY region), 1) AS pct_of_region,
       ROUND(100.0 * revenue / SUM(revenue) OVER (), 1)                    AS pct_of_all
FROM monthly_sales
ORDER BY region, month;

Step 3: Ranking – ROW_NUMBER, RANK and DENSE_RANK

Rank each region’s months from best to worst:

Table comparing ranking functions on revenues 110, 95, 80, 80 and 75: ROW_NUMBER gives 1 to 5, RANK gives 1, 2, 3, 3, 5 and DENSE_RANK gives 1, 2, 3, 3, 4
How the three ranking functions treat a tie.
SELECT region, month, revenue,
       ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC) AS row_num,
       RANK()       OVER (PARTITION BY region ORDER BY revenue DESC) AS rnk,
       DENSE_RANK() OVER (PARTITION BY region ORDER BY revenue DESC) AS dense_rnk
FROM monthly_sales
WHERE region = 'East';

East has two months tied on 80, which shows the difference:

  • ROW_NUMBER gives unique numbers 1, 2, 3, 4 – ties are broken arbitrarily.
  • RANK gives ties the same rank and then skips: 1, 2, 3, 3.
  • DENSE_RANK gives ties the same rank without gaps: 1, 2, 3, 3.

The gap appears only after a tie in the middle; with values 110, 95, 80, 80 the tie is at the end, so RANK and DENSE_RANK match here. If a tie were in first place, RANK would give 1, 1, 3 and DENSE_RANK 1, 1, 2.

Step 4: Top N per group

A classic use: the best month for each region. You cannot use a window function directly in WHERE (it is calculated after WHERE), so wrap it in a CTE:

WITH ranked AS (
    SELECT region, month, revenue,
           ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC) AS rn
    FROM monthly_sales
)
SELECT region, month, revenue
FROM ranked
WHERE rn = 1
ORDER BY revenue DESC;

Use RANK instead of ROW_NUMBER if you want to keep all tied rows. The same pattern de-duplicates data: number the rows within each duplicate group, ordered by last-updated date, and keep row 1. CTEs are explained in CTEs vs Subqueries.

Step 5: LAG and LEAD – compare with previous or next rows

SELECT region, month, revenue,
       LAG(revenue) OVER (PARTITION BY region ORDER BY month) AS prev_month,
       revenue - LAG(revenue) OVER (PARTITION BY region ORDER BY month) AS change,
       ROUND(100.0 * (revenue - LAG(revenue) OVER (PARTITION BY region ORDER BY month))
             / LAG(revenue) OVER (PARTITION BY region ORDER BY month), 1) AS pct_change,
       LEAD(revenue) OVER (PARTITION BY region ORDER BY month) AS next_month
FROM monthly_sales
ORDER BY region, month;

LAG looks back one row (or more: LAG(revenue, 12) for the same month last year in monthly data); LEAD looks forward. The first month in each partition has no previous row, so LAG returns NULL. You can supply a default as the third argument, but NULL is usually more honest than pretending the previous value was zero.

Repeating the same window is verbose. SQLite, PostgreSQL and MySQL support a named window clause to tidy this up:

SELECT region, month, revenue,
       LAG(revenue) OVER w AS prev_month,
       revenue - LAG(revenue) OVER w AS change
FROM monthly_sales
WINDOW w AS (PARTITION BY region ORDER BY month)
ORDER BY region, month;

Step 6: Running totals

Add ORDER BY inside OVER with SUM and you get a cumulative total:

Table for the North region showing monthly revenue 100, 120, 90 and 150, a running total of 100, 220, 310 and 460, and LAG values NULL, 100, 120 and 90
A window function adds a calculation to each row without collapsing rows.
SELECT region, month, revenue,
       SUM(revenue) OVER (PARTITION BY region ORDER BY month
                          ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total
FROM monthly_sales
ORDER BY region, month;

That ROWS BETWEEN ... part is the frame: which rows within the partition are included for the current row. Here it is “everything from the start up to this row”.

Step 7: Frames and moving averages

Change the frame to calculate a moving average over the current and previous two months:

SELECT region, month, revenue,
       ROUND(AVG(revenue) OVER (PARTITION BY region ORDER BY month
                                ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 1) AS moving_avg_3m
FROM monthly_sales
ORDER BY region, month;

For the first two months there are fewer than three rows, so the average uses what is available. Bear this in mind when presenting early values.

A subtle default: if you specify ORDER BY in the window but no frame, most databases use RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. With RANGE, rows with the same ORDER BY value are treated as peers and included together, so running totals can jump in steps when there are ties. Specifying ROWS explicitly avoids surprises.

Step 8: NTILE for buckets

NTILE(n) splits ordered rows into n roughly equal groups – handy for quartiles or customer segments:

SELECT region, month, revenue,
       NTILE(4) OVER (ORDER BY revenue DESC) AS revenue_quartile
FROM monthly_sales
ORDER BY revenue DESC;

Quartile 1 contains the top-earning quarter of region-months.

Step 9: FIRST_VALUE and comparisons with a baseline

SELECT region, month, revenue,
       FIRST_VALUE(revenue) OVER (PARTITION BY region ORDER BY month) AS jan_revenue,
       ROUND(100.0 * revenue / FIRST_VALUE(revenue) OVER (PARTITION BY region ORDER BY month), 1)
           AS index_vs_jan
FROM monthly_sales
ORDER BY region, month;

Indexing each region to its January value (January = 100) makes growth comparable between large and small regions.

Where window functions fit in a query

Window functions are evaluated after WHERE, GROUP BY and HAVING, but before the final ORDER BY. That means:

  • You cannot filter on them in WHERE – use a CTE or subquery.
  • You can apply them to grouped results, for example SUM(SUM(revenue)) OVER () for a share of a grouped total.
  • WHERE filters rows before the window sees them, which changes totals and rankings. Filter in an outer query if you want rankings computed on all rows.

Common mistakes

  • Filtering on a window function in WHERE. Wrap it in a CTE.
  • Forgetting ORDER BY inside OVER for LAG, LEAD, running totals and rankings.
  • Relying on the default RANGE frame with tied ORDER BY values.
  • Using ROW_NUMBER where ties matter, arbitrarily dropping tied rows.
  • Gaps in time series. LAG returns the previous row, not the previous month. If a month is missing, “previous” is two months back. Fill gaps first.
  • Integer division in percentages – multiply by 100.0.

FAQ

Are window functions slow?

They usually require sorting each partition, which costs time on very large tables, but they are typically far faster than equivalent self-joins. Indexes on the partition and order columns can help.

Can I use window functions in pandas?

Yes: groupby().transform(), groupby().rank(), groupby().shift() and groupby().cumsum() are the equivalents. See pandas groupby Explained.

Does Excel or Power BI have something similar?

In Power BI, DAX functions such as RANKX and time-intelligence functions fill a similar role – see DAX Measures for Beginners.

Next steps

Make sure you are comfortable with GROUP BY and HAVING and joins, then learn to structure longer queries with CTEs.

LJ

About the author: Lucky Joseph

Lucky is a UK-based writer with a data science background who runs DataScienceWay. Every tutorial is tested before publication; if you spot something that no longer works, please get in touch.

More about DataScienceWay · Contact