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 BYandORDER BY - Ranking with
ROW_NUMBER,RANKandDENSE_RANK - Aggregates as window functions: averages and running totals
- Looking at neighbouring rows with
LAGandLEAD - 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()withoutPARTITION BYranks 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. WithGROUP BYyou would get one row per department and lose the names.
| Scores | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 95 | 1 | 1 | 1 |
| 90 | 2 | 2 | 2 |
| 90 | 3 | 2 | 2 |
| 85 | 4 | 4 | 3 |
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: addingORDER BYinsideOVERmakes 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).LEADlooks 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
- Filtering with
WHERE rank_col = 1in the same query that defines it; use a CTE. - Forgetting
ORDER BYinOVERfor ranking or running totals, which gives arbitrary results. - Choosing
ROW_NUMBERwhen ties matter; one of two equal scores would be dropped from a “top 1”. - Confusing the query’s final
ORDER BYwith the one insideOVER; 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 BYsets the groups;ORDER BYinsideOVERsets the order.ROW_NUMBER,RANKandDENSE_RANKdiffer only on ties.- Filter window results in an outer query or CTE.
Next: SQL Transactions.
