DEV Community

Ihsan the analyst
Ihsan the analyst

Posted on

15 SQL window function problems you can run right now (with answers)

Window functions are the part of SQL that separates "I can write a query" from "I actually know SQL." Most tutorials explain the syntax and stop — but the only way it clicks is to solve problems.

So here are a few, built on one tiny sales table so you can run them anywhere (Postgres, MySQL 8+, SQL Server, SQLite 3.25+).

1. Number each sale per region, newest first

ROW_NUMBER() OVER (PARTITION BY region ORDER BY sale_date DESC)
Enter fullscreen mode Exit fullscreen mode

The key insight: PARTITION BY restarts the count for each group, and ORDER BY decides what "first" means.

2. Running total of sales over time

SUM(amount) OVER (ORDER BY sale_date)
Enter fullscreen mode Exit fullscreen mode

No PARTITION BY = one running total for everything. Add PARTITION BY region and you get a running total per region.

3. Compare each sale to the rep's previous sale

LAG(amount) OVER (PARTITION BY rep ORDER BY sale_date)
Enter fullscreen mode Exit fullscreen mode

The gotcha: the first row has no previous row, so it returns NULL. Fix it with a default: LAG(amount, 1, 0).

The mistake that still catches me

LAST_VALUE() only looks as far as the current row by default, so it quietly returns the wrong answer until you set the frame to UNBOUNDED FOLLOWING.

Want all 15?

I put together 15 of these — ranking, running totals, LAG/LEAD, NTILE — each with a ready-to-run answer and a short explanation, built on that one simple table.

Full set here: SQL Window Functions: 15 Practice Problems (with Answers)

What's the window function that took you longest to really understand?

Top comments (0)