Reading history

SQL Window Functions: ROW_NUMBER, RANK, LAG and Running Totals

5 min read 0 views

Learn SQL window functions: OVER, PARTITION BY, ROW_NUMBER vs RANK vs DENSE_RANK, running totals, LAG and LEAD, frames, and top-N per group.

GROUP BY collapses many rows into one summary row. Window functions calculate across a set of related rows but keep every row in the result. That makes it easy to rank students within their department, show a running total next to each order, or compare a value with the previous one, all of which are awkward without them. They are supported by PostgreSQL, MySQL 8, SQL Server, Oracle and SQLite 3.25+.

In this lesson you will learn

  • The OVER() clause, PARTITION BY and ORDER BY
  • Ranking with ROW_NUMBER, RANK and DENSE_RANK
  • Aggregates as window functions: averages and running totals
  • Looking at neighbouring rows with LAG and LEAD
  • Filtering on a window result (top N per group)

How OVER() Works

function_name(...) OVER (
    PARTITION BY column   -- optional: split rows into groups
    ORDER BY column       -- optional: order rows inside each group
)

The window is the set of rows the function looks at for the current row. PARTITION BY works like GROUP BY but without merging rows; leaving it out makes the whole result one window.

Ranking and Group Averages

-- Rank students inside each department without collapsing rows
SELECT name, dept, cgpa,
       ROW_NUMBER() OVER (PARTITION BY dept ORDER BY cgpa DESC) AS row_num,
       RANK()       OVER (ORDER BY cgpa DESC) AS overall_rank,
       ROUND(AVG(cgpa) OVER (PARTITION BY dept), 2) AS dept_avg
FROM students
WHERE cgpa IS NOT NULL
ORDER BY dept, row_num;

Output

+--------+------+------+---------+--------------+----------+
| name   | dept | cgpa | row_num | overall_rank | dept_avg |
+--------+------+------+---------+--------------+----------+
| Sabbir | BBA  | 3.55 | 1       | 4            | 3.33     |
| Imran  | BBA  | 3.1  | 2       | 6            | 3.33     |
| Tania  | CSE  | 3.95 | 1       | 1            | 3.81     |
| Nusrat | CSE  | 3.82 | 2       | 2            | 3.81     |
| Mitu   | CSE  | 3.67 | 3       | 3            | 3.81     |
| Arif   | EEE  | 3.41 | 1       | 5            | 3.2      |
| Rafi   | EEE  | 2.98 | 2       | 7            | 3.2      |
+--------+------+------+---------+--------------+----------+
(7 rows)
  • ROW_NUMBER() numbers rows 1, 2, 3 within each department, restarting for every partition.
  • RANK() without PARTITION BY ranks all students together. Tania is first overall.
  • AVG(cgpa) OVER (PARTITION BY dept) puts the department average on every row, so each student can be compared with it directly. With GROUP BY you would get one row per department and lose the names.
ScoresROW_NUMBERRANKDENSE_RANK
95111
90222
90322
85443

With ties, ROW_NUMBER still gives unique numbers, RANK leaves a gap after the tie, and DENSE_RANK does not.

Running Totals, LAG and Top-N

-- Running total and previous order per customer
SELECT customer, order_date, amount,
       SUM(amount) OVER (PARTITION BY customer ORDER BY order_date) AS running_total,
       LAG(amount) OVER (PARTITION BY customer ORDER BY order_date) AS previous_amount
FROM orders
WHERE status <> 'cancelled' AND amount IS NOT NULL
ORDER BY customer, order_date;

-- Top 3 salaries: filter on a window function result via a CTE
WITH ranked AS (
    SELECT name, title, salary,
           RANK() OVER (ORDER BY salary DESC) AS pay_rank
    FROM employees
)
SELECT * FROM ranked WHERE pay_rank <= 3;

Output

+----------+------------+--------+---------------+-----------------+
| customer | order_date | amount | running_total | previous_amount |
+----------+------------+--------+---------------+-----------------+
| Joya     | 2026-02-14 | 2300   | 2300          | NULL            |
| Joya     | 2026-03-21 | 300    | 2600          | 2300            |
| Karim    | 2026-01-05 | 1200   | 1200          | NULL            |
| Karim    | 2026-03-09 | 1500   | 2700          | 1200            |
| Rina     | 2026-01-18 | 450    | 450           | NULL            |
| Rina     | 2026-02-27 | 650    | 1100          | 450             |
+----------+------------+--------+---------------+-----------------+
(6 rows)

+---------+-------+--------+----------+
| name    | title | salary | pay_rank |
+---------+-------+--------+----------+
| Shahana | CEO   | 250000 | 1        |
| Faisal  | CTO   | 180000 | 2        |
| Lipi    | CFO   | 170000 | 3        |
+---------+-------+--------+----------+
(3 rows)
  • SUM(amount) OVER (PARTITION BY customer ORDER BY order_date) is a running total: adding ORDER BY inside OVER makes the window grow from the first row up to the current one.
  • LAG(amount) returns the value from the previous row in the window (NULL for the first). LEAD looks at the next row. Both are useful for “change since last time” reports.
  • Window functions are calculated after WHERE, so you cannot filter on them directly. Wrap the query in a CTE or subquery and filter outside, as the top-3 salary query does.

Window Frames (Optional Detail)

-- Average of the current order and the two before it
AVG(amount) OVER (ORDER BY order_date
                  ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)

A frame clause sets exactly which rows around the current one are included. It is how moving averages are calculated.

Common Mistakes

  1. Filtering with WHERE rank_col = 1 in the same query that defines it; use a CTE.
  2. Forgetting ORDER BY in OVER for ranking or running totals, which gives arbitrary results.
  3. Choosing ROW_NUMBER when ties matter; one of two equal scores would be dropped from a “top 1”.
  4. Confusing the query’s final ORDER BY with the one inside OVER; they are independent.

Practice Exercises

Exercise 1. Show each employee’s salary and the difference from the company average salary.

Show answer
SELECT name, salary,
       salary - ROUND(AVG(salary) OVER ()) AS diff_from_avg
FROM employees;

An empty OVER () makes the whole table one window.

Exercise 2. Find the top-scoring student in each department.

Show answer
WITH r AS (
    SELECT name, dept, cgpa,
           RANK() OVER (PARTITION BY dept ORDER BY cgpa DESC) AS rk
    FROM students
    WHERE cgpa IS NOT NULL
)
SELECT name, dept, cgpa FROM r WHERE rk = 1;

Frequently Asked Questions

What is the difference between GROUP BY and PARTITION BY?

GROUP BY returns one row per group. PARTITION BY divides rows into groups for a window function but keeps every original row in the result.

Can I use several window functions in one query?

Yes. Each has its own OVER clause. If many share the same window, a named WINDOW w AS (...) clause avoids repeating it.

Summary

  • Window functions compute over related rows without collapsing them.
  • PARTITION BY sets the groups; ORDER BY inside OVER sets the order.
  • ROW_NUMBER, RANK and DENSE_RANK differ only on ties.
  • Filter window results in an outer query or CTE.

Next: SQL Transactions.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *