← Guides

SQL Window Functions for Beginners: Running Totals, Rankings and Month-over-Month

ROW_NUMBER, RANK, SUM OVER and LAG explained on a sales table, with the business questions each one answers.

SQL · 8 min read

By the FormulAI editorial team · Reviewed November 19, 2026

Sample data used in this guide

Table monthly_sales (monthly revenue).
monthrevenue
2025-011000
2025-021200
2025-03900
2025-041500
2025-051500
Table product_sales (category, product, revenue).
categoryproductrevenue
LaptopsA900
LaptopsB700
LaptopsC700
LaptopsD300
PhonesX500
PhonesY400

What a window function does

A window function computes a value across a set of rows related to the current row, without collapsing them like GROUP BY does. You keep every detail row and add a column such as a rank or a running total. The OVER() clause defines the window: PARTITION BY splits it into groups and ORDER BY sets the order inside each group.

Running total

Cumulative revenue per month is a single line with SUM() OVER (ORDER BY month).

SELECT month, revenue,
       SUM(revenue) OVER (ORDER BY month) AS cumulative
FROM monthly_sales;
Running total result:
monthrevenuecumulative
2025-0110001000
2025-0212002200
2025-039003100
2025-0415004600
2025-0515006100

Top N per group

"Best 3 products per category" is the classic question GROUP BY cannot answer. Number the rows inside each category, then filter.

SELECT * FROM (
  SELECT category, product, revenue,
         ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) AS rn
  FROM product_sales
) t
WHERE rn <= 3;
Top 3 per category. B and C are tied: ROW_NUMBER gives them 2 and 3 in a non-guaranteed order.
categoryproductrevenuern
LaptopsA9001
LaptopsB7002
LaptopsC7003
PhonesX5001
PhonesY4002

ROW_NUMBER vs RANK vs DENSE_RANK

With two products tied at the same revenue, ROW_NUMBER gives 1 and 2 arbitrarily, RANK gives 1, 1, 3 and DENSE_RANK gives 1, 1, 2. Pick RANK for leaderboards where ties matter, ROW_NUMBER when you need exactly N rows.

The three functions on the Laptops category:
productrevenueROW_NUMBERRANKDENSE_RANK
A900111
B700222
C700322
D300443

Month-over-month growth with LAG

LAG reads the previous row's value. Divide by it to get growth, and protect against division by zero with NULLIF.

SELECT month, revenue,
       ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
             / NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 1) AS growth_pct
FROM monthly_sales;
Month-over-month growth:
monthrevenuegrowth_pct
2025-011000NULL
2025-02120020.0
2025-03900-25.0
2025-04150066.7
2025-0515000.0

Compatibility notes

Window functions are supported by PostgreSQL, SQL Server, Oracle, SQLite 3.25+, MySQL 8+ and BigQuery. On MySQL 5.7 they do not exist and must be rewritten with self-joins or variables. Mention your database engine when you ask FormulAI so the generated syntax matches.

Common errors and how to fix them

ERROR: window functions are not allowed in WHERE

Cause: Window functions are computed after WHERE, so you cannot filter on them directly (SQL Server: "Windowed functions can only appear in the SELECT or ORDER BY clauses").

Fix: Compute them in a subquery or CTE, then filter outside, as in the Top N example.

ERROR 1064: You have an error in your SQL syntax ... near '(ORDER BY month)'

Cause: The server runs MySQL 5.7 or older, which has no window functions.

Fix: Upgrade to MySQL 8 or MariaDB 10.2+, or replace the running total with a correlated subquery.

ERROR: division by zero

Cause: The previous month is 0 in the growth calculation.

Fix: Wrap the denominator in NULLIF(..., 0): the result becomes NULL instead of an error.

No message: the running total jumps on tied rows

Cause: With ORDER BY alone the default frame is RANGE, so rows sharing the same sort value are added together.

Fix: Specify ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, or add a unique column to the sort.

FAQ

How is this different from GROUP BY?

GROUP BY collapses each group into one row. A window function keeps every row and adds a column computed over the group.

Can one query use several windows?

Yes. To avoid repeating the definition, declare it once with WINDOW w AS (ORDER BY month) and write OVER w (PostgreSQL, MySQL 8).

Are these functions slow?

They require a sort. An index on the PARTITION BY and ORDER BY columns often avoids that sort on large tables.

Go further

How this guide was made

Every formula, query and script in this guide was run on a real sample file (Excel 365, Google Sheets, PostgreSQL, MySQL or Python 3) before publication. We document the edge cases we hit during testing, such as text-formatted numbers, empty months or NULL values. AI helps us draft and translate; a human checks each example and updates the guide when software versions change. Spotted an error? Write to contact@formulai-app.com.