Pulse Data Hub

SQL Window Functions Explained with Real Queries

SQL window functions calculate across a set of related rows without collapsing them into one row, the way GROUP BY does. They are how you write running totals, rankings and “compared with the previous row” in a single query. This guide runs every query in SQLite against a real sample database and shows the actual results.

The data is the Chinook sample database: a fictional digital music store with customers, invoices and tracks. It has 412 invoices from 2021 to 2025 and a total revenue of 2,328.60. Because it is a teaching database, the figures are not a real company, and as you will see its sales are unusually even. Everything ran on SQLite 3.53.1, which supports window functions from version 3.25.

Horizontal bar chart of revenue by billing country in the Chinook sample store: USA 523.06, Canada 303.96, France 195.10, Brazil 190.10, Germany 156.48, United Kingdom 112.86.
Revenue by billing country in the Chinook sample database, the ranking used in the rank() example.

Load the database

import sqlite3, urllib.request, pandas as pd

url = "https://raw.githubusercontent.com/lerocha/chinook-database/master/ChinookDatabase/DataSources/Chinook_Sqlite.sqlite"
urllib.request.urlretrieve(url, "chinook.sqlite")
con = sqlite3.connect("chinook.sqlite")

def q(sql):
    print(pd.read_sql(sql, con).to_string(index=False))

SQL window functions: OVER turns an aggregate into a window

A normal aggregate with GROUP BY returns one row per group. Add OVER (...) and the same function returns a value on every row, computed over a window of rows. Compare the two on the same table.

q("""
SELECT substr(InvoiceDate, 1, 4) AS yr, COUNT(*) AS invoices, ROUND(SUM(Total), 2) AS revenue
FROM Invoice GROUP BY yr
""")
q("""
SELECT InvoiceId, CustomerId, Total,
       ROUND(AVG(Total) OVER (PARTITION BY CustomerId), 2) AS customer_avg,
       ROUND(Total - AVG(Total) OVER (PARTITION BY CustomerId), 2) AS diff
FROM Invoice ORDER BY diff DESC LIMIT 3
""")

Output:

  yr  invoices  revenue
2021        83   449.46
2022        83   481.45
2023        83   469.58
2024        83   477.53
2025        80   450.58
 InvoiceId  CustomerId  Total  customer_avg  diff
       404           6  25.86          7.09 18.77
       299          26  23.86          6.80 17.06
        96          45  21.86          6.52 15.34

The first query reduces 412 invoices to five rows. The second keeps all 412 rows and adds each customer’s own average next to every invoice. Customer 6’s largest invoice (25.86) is 18.77 above that customer’s average of 7.09. PARTITION BY is the window’s GROUP BY, and ORDER BY inside OVER sets the order the function sees the rows.

Running totals and moving averages

q("""
WITH m AS (SELECT substr(InvoiceDate, 1, 7) AS ym, ROUND(SUM(Total), 2) AS rev FROM Invoice GROUP BY ym)
SELECT ym, rev,
       ROUND(SUM(rev) OVER (ORDER BY ym), 2) AS running,
       ROUND(AVG(rev) OVER (ORDER BY ym ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS avg3
FROM m LIMIT 5
""")

Output:

     ym   rev  running  avg3
2021-01 35.64    35.64 35.64
2021-02 37.62    73.26 36.63
2021-03 37.62   110.88 36.96
2021-04 37.62   148.50 37.62
2021-05 37.62   186.12 37.62

SUM() OVER (ORDER BY ym) adds the months up as it goes. The ROWS BETWEEN 2 PRECEDING AND CURRENT ROW frame limits the average to the current and two earlier months. The numbers here are almost flat (35.64, then 37.62 every month shown), which is a quirk of the sample data, not a pattern in real stores.

Ranking: rank, dense_rank and row_number

The three differ only when values tie. Invoices 96 and 194 both total 21.86, which makes the tie visible.

q("""
SELECT InvoiceId, Total,
       RANK() OVER (ORDER BY Total DESC) AS rk,
       DENSE_RANK() OVER (ORDER BY Total DESC) AS drk,
       ROW_NUMBER() OVER (ORDER BY Total DESC) AS rn
FROM Invoice ORDER BY Total DESC LIMIT 8
""")

Output:

 InvoiceId  Total  rk  drk  rn
       404  25.86   1    1   1
       299  23.86   2    2   2
        96  21.86   3    3   3
       194  21.86   3    3   4
        89  18.86   5    4   5
       201  18.86   5    4   6
        88  17.91   7    5   7
       306  16.86   8    6   8

After the tie at 21.86, RANK skips to 5 (rows 3 and 3, then 5), DENSE_RANK continues with 4, and ROW_NUMBER always counts 1, 2, 3, 4 and breaks the tie arbitrarily. Use ROW_NUMBER when you need exactly one row per group, as in the next example, and RANK or DENSE_RANK when equal values should share a place.

The ranking can sit on top of a GROUP BY too. Countries by revenue, as in the chart above, only need the sum inside the window’s ORDER BY:

q("""
SELECT BillingCountry, ROUND(SUM(Total), 2) AS revenue,
       RANK() OVER (ORDER BY SUM(Total) DESC) AS rk
FROM Invoice GROUP BY BillingCountry ORDER BY revenue DESC LIMIT 5
""")

Output:

BillingCountry  revenue  rk
           USA   523.06   1
        Canada   303.96   2
        France   195.10   3
        Brazil   190.10   4
       Germany   156.48   5

Top row per group

A classic interview question: the biggest customer in each country. Number the rows inside each partition, then keep number 1. The window result cannot be filtered in the same SELECT, so it goes in a subquery.

q("""
SELECT * FROM (
  SELECT BillingCountry, CustomerId, ROUND(SUM(Total), 2) AS spent,
         ROW_NUMBER() OVER (PARTITION BY BillingCountry ORDER BY SUM(Total) DESC) AS rn
  FROM Invoice GROUP BY BillingCountry, CustomerId
) WHERE rn = 1 ORDER BY spent DESC LIMIT 4
""")

Output:

BillingCountry  CustomerId  spent  rn
Czech Republic           6  49.62   1
           USA          26  47.62   1
         Chile          57  46.62   1
       Hungary          45  45.62   1

Compare with the previous row: LAG

q("""
SELECT yr, revenue, ROUND(revenue - LAG(revenue) OVER (ORDER BY yr), 2) AS change
FROM (SELECT substr(InvoiceDate, 1, 4) AS yr, SUM(Total) AS revenue FROM Invoice GROUP BY yr)
""")
q("""
SELECT CustomerId, InvoiceDate,
       CAST(julianday(InvoiceDate) - julianday(LAG(InvoiceDate) OVER (PARTITION BY CustomerId ORDER BY InvoiceDate)) AS INT) AS days_since_last
FROM Invoice WHERE CustomerId = 6 LIMIT 4
""")

Output:

  yr  revenue  change
2021   449.46     NaN
2022   481.45   31.99
2023   469.58  -11.87
2024   477.53    7.95
2025   450.58  -26.95
 CustomerId         InvoiceDate  days_since_last
          6 2021-07-11 00:00:00              NaN
          6 2023-02-15 00:00:00            584.0
          6 2023-05-20 00:00:00             94.0
          6 2023-08-22 00:00:00             94.0

Revenue rose 31.99 in 2022, fell 11.87 in 2023, rose 7.95 in 2024 and fell 26.95 in 2025. The 2025 drop needs care: the data ends on 22 December 2025 and 2025 has 80 invoices against 83 in every other year, so the year may be incomplete. The first row of LAG is NULL because there is no previous row. The second query shows customer 6 waiting 584 days between its first two invoices, then 94 days between the next ones.

Split into groups: NTILE

q("""
SELECT quartile, COUNT(*) AS customers, ROUND(MIN(s), 2) AS lowest, ROUND(MAX(s), 2) AS highest, ROUND(SUM(s), 2) AS revenue
FROM (SELECT SUM(Total) AS s, NTILE(4) OVER (ORDER BY SUM(Total)) AS quartile FROM Invoice GROUP BY CustomerId)
GROUP BY quartile
""")

Output:

 quartile  customers  lowest  highest  revenue
        1         15   36.64    37.62   563.32
        2         15   37.62    37.62   564.30
        3         15   37.62    39.62   586.30
        4         14   40.62    49.62   614.68

NTILE(4) cuts the 59 customers into spend quartiles (15, 15, 15 and 14 customers). In a real store the top quartile usually earns far more than the bottom. Here the top quartile brings in 614.68 and the bottom 563.32, which tells you this is a synthetic dataset where every customer spends about the same. It is a good reminder to look at the output before reading a story into it.

The error everyone hits

try:
    pd.read_sql("SELECT Total, RANK() OVER (ORDER BY Total) AS r FROM Invoice WHERE r = 1", con)
except Exception as e:
    print(e)

Output:

Execution failed on sql 'SELECT Total, RANK() OVER (ORDER BY Total) AS r FROM Invoice WHERE r = 1': misuse of aliased window function r

SQL evaluates WHERE before window functions, so you cannot filter on a window result there. Wrap the query in a subquery or CTE, as in the top-row example, and filter outside. For the GROUP BY basics and joins that come first, see SQL for data analysis; for the same ideas in Python, try the pandas groupby guide or the pandas cheat sheet. The free CSV to SQL tool turns your own file into a table you can practise on.

The full list of functions and frame options is in the SQLite window functions documentation, and the database is from the Chinook GitHub repository. The syntax shown works in PostgreSQL, MySQL 8 and SQL Server too, but I only ran it on SQLite, and I did not test FIRST_VALUE, LEAD or RANGE frames.

FAQ

What are SQL window functions?

Functions that calculate across a set of rows related to the current row, using OVER, while still returning every row. Examples are ROW_NUMBER, RANK, LAG, SUM OVER and NTILE.

What is the difference between GROUP BY and a window function?

GROUP BY collapses rows into one per group. A window function keeps all rows and adds a calculated column. In the example above, 412 invoices stayed 412 rows.

What is the difference between RANK and DENSE_RANK?

After a tie, RANK leaves a gap (1, 2, 3, 3, 5) and DENSE_RANK does not (1, 2, 3, 3, 4). ROW_NUMBER never repeats a number.

Why can’t I use a window function in WHERE?

Window functions run after WHERE and GROUP BY in the order of evaluation. Put the query in a subquery or CTE and filter the result in the outer query.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights