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

SQL Server 6 min readUpdated Nov 20, 2026
4 views0 comments

Two features make complex T-SQL far easier to write: common table expressions (CTEs), which split a big query into named steps, and window functions, which rank rows, build running totals and compare a row with the previous one without losing any detail. This guide teaches both with the same small sample tables.

Part of the SQL Server for Beginners series. This article is the written version of lesson 7 of the Bigland Network video course, with the same sample data. The results shown were worked out by hand from that data, so run every example on a test database, not on production data.

Watch lesson 7 as a video or open it on YouTube. The written lesson below follows the same steps and the same sample data.


Contents

1. Common table expressions (CTEs)

Long queries with subqueries inside subqueries are hard to read. A CTE is a named temporary result that you define with WITH. Split the big query into small named steps, then use each step like a table. A CTE exists only for the one statement that follows it and stores no data. The examples use the tables from Lesson 2: JOINs.

WITH HighPaid AS (
    SELECT FirstName, Salary
    FROM Employees
    WHERE Salary > 4000
)
SELECT FirstName, Salary
FROM HighPaid
ORDER BY Salary DESC;
FirstName Salary
Youssef 5200
Nadia 4800
Amina 4200

A CTE is most useful when you join it. Employees who earn more than their department average (compare with the correlated subquery in Lesson 3: GROUP BY, HAVING and Subqueries):

WITH DeptAvg AS (
    SELECT DeptId, AVG(Salary) AS AvgSalary
    FROM Employees
    GROUP BY DeptId
)
SELECT e.FirstName, e.Salary, a.AvgSalary
FROM Employees e
INNER JOIN DeptAvg a ON e.DeptId = a.DeptId
WHERE e.Salary > a.AvgSalary;
FirstName Salary AvgSalary
Amina 4200 3900
Youssef 5200 5000

Several CTEs in one query

Write WITH once and separate the CTEs with commas. A later CTE can use an earlier one:

WITH DeptTotal AS (
    SELECT DeptId, SUM(Salary) AS Total FROM Employees GROUP BY DeptId
),
BigDepts AS (
    SELECT DeptId, Total FROM DeptTotal WHERE Total > 5000
)
SELECT d.DeptName, b.Total
FROM BigDepts b
INNER JOIN Departments d ON d.DeptId = b.DeptId;
DeptName Total
Sales 7800
IT 10000
  • A CTE lives for one statement (SELECT, INSERT, UPDATE or DELETE).
  • The statement before WITH must end with a semicolon.
  • A CTE is a name for a query, not stored data.

Recursive CTE

A CTE can call itself. It has an anchor part and a recursive part joined by UNION ALL. Always add a stop condition, or the query loops until SQL Server stops it (the default limit is 100 levels).

WITH Numbers AS (
    SELECT 1 AS n
    UNION ALL
    SELECT n + 1 FROM Numbers WHERE n < 5
)
SELECT n FROM Numbers;
n
1
2
3
4
5

Recursive CTEs are ideal for hierarchies such as employees and managers.

2. Window functions

GROUP BY collapses many rows into one per group and you lose the details. A window function calculates over a group of rows but keeps every row. The OVER clause defines the window with PARTITION BY (the groups) and ORDER BY (the order inside the group).

ROW_NUMBER

SELECT FirstName, Salary,
       ROW_NUMBER() OVER (ORDER BY Salary DESC) AS rn
FROM Employees;
FirstName Salary rn
Youssef 5200 1
Nadia 4800 2
Amina 4200 3
Omar 3900 4
Salma 3600 5
Karim 3100 6

Add PARTITION BY and the numbering restarts for each group:

SELECT FirstName, DeptId, Salary,
       ROW_NUMBER() OVER (PARTITION BY DeptId ORDER BY Salary DESC) AS rn
FROM Employees;
FirstName DeptId Salary rn
Omar NULL 3900 1
Amina 1 4200 1
Salma 1 3600 2
Youssef 2 5200 1
Nadia 2 4800 2
Karim 3 3100 1

RANK and DENSE_RANK

If two employees earned 4800: ROW_NUMBER still gives different numbers (2 and 3), RANK gives both 2 and then skips to 4, and DENSE_RANK gives both 2 and continues with 3, with no gap. Choose the one that matches your tie rule.

Top row of each group

You cannot filter on ROW_NUMBER in WHERE, so put the ranking in a CTE:

WITH Ranked AS (
    SELECT FirstName, DeptId, Salary,
           ROW_NUMBER() OVER (PARTITION BY DeptId ORDER BY Salary DESC) AS rn
    FROM Employees
)
SELECT FirstName, DeptId, Salary
FROM Ranked
WHERE rn = 1;
FirstName DeptId Salary
Omar NULL 3900
Amina 1 4200
Youssef 2 5200
Karim 3 3100

Running totals and group values

SELECT FirstName, Salary,
       SUM(Salary) OVER (ORDER BY Id ROWS UNBOUNDED PRECEDING) AS RunningTotal
FROM Employees;
FirstName Salary RunningTotal
Amina 4200 4200
Youssef 5200 9400
Salma 3600 13000
Karim 3100 16100
Nadia 4800 20900
Omar 3900 24800

With PARTITION BY and no ORDER BY, an aggregate shows the group value on every row, with no GROUP BY or join:

SELECT FirstName, Salary,
       AVG(Salary) OVER (PARTITION BY DeptId) AS DeptAvg
FROM Employees;

Amina and Salma show 3900, Youssef and Nadia show 5000, Karim shows 3100 and Omar shows 3900.

LAG and LEAD

SELECT FirstName, Salary,
       LAG(Salary)  OVER (ORDER BY Id) AS PrevSal,
       LEAD(Salary) OVER (ORDER BY Id) AS NextSal
FROM Employees;
FirstName Salary PrevSal NextSal
Amina 4200 NULL 5200
Youssef 5200 4200 3600
Salma 3600 5200 3100
Karim 3100 3600 4800
Nadia 4800 3100 3900
Omar 3900 4800 NULL

Use LAG to compare a month with the previous month or to calculate the difference between two rows.

3. Rules, mistakes and best practices

  • Window functions are allowed only in SELECT and ORDER BY, never in WHERE. Use a CTE to filter on a rank.
  • ROW_NUMBER, RANK, DENSE_RANK and LAG need an ORDER BY inside OVER.
  • PARTITION BY is optional: without it the whole result is one window.
  • Forgetting the semicolon before WITH.
  • A recursive CTE without a stop condition.
  • Best practice: one step, one name; clear names for CTEs and window columns; index the PARTITION BY and ORDER BY columns on big tables (SQL Server Indexes Explained: Clustered, Nonclustered and Covering); prefer window functions to correlated subqueries.

4. Practice

  • Write a CTE that selects employees earning more than 4500, then select from it.
  • Rank all employees by salary, highest first, with RANK.
  • Show each employee’s salary and the total salary of their department with SUM OVER.

Answers: (1) WITH BigEarners AS (SELECT FirstName, Salary FROM Employees WHERE Salary > 4500) SELECT * FROM BigEarners; returns Youssef and Nadia. (2) RANK() OVER (ORDER BY Salary DESC) gives ranks 1 to 6, Youssef first and Karim last, as there are no ties. (3) SUM(Salary) OVER (PARTITION BY DeptId) shows 7800 for Amina and Salma, 10000 for Youssef and Nadia, 3100 for Karim and 3900 for Omar.

Frequently asked questions

CTE or temp table?

A CTE lasts for one statement and stores nothing. A temp table is a real table in tempdb that lasts for the session and can be indexed. See Lesson 9: Functions, Temp Tables and Table Variables.

What is the difference between RANK and DENSE_RANK?

Both give tied rows the same rank. RANK skips the following numbers (1, 2, 2, 4) and DENSE_RANK does not (1, 2, 2, 3).

Can I use a window function in WHERE?

No. Put the query in a CTE or subquery, then filter on the result column.

What to learn next

Next, learn the built-in functions you will use in almost every query in Lesson 8: Built-in Functions. Previous lesson: Lesson 6: Indexes, Views and Stored Procedures.

The whole series

Sources and further reading

  • Microsoft Learn, Transact-SQL reference (Database Engine), on learn.microsoft.com: the official syntax for every statement used here.
  • Microsoft Learn, SQL Server documentation, for SQL Server Management Studio (SSMS) and the sample concepts.
Did you find this helpful?Tap the heart to let us know. It takes one second and no account.

More tutorials like this

Leave a Comment

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

Bigland Network IT

Practical tutorials for people who run, build and fix things: operating systems, databases, development, networking and security.

Topics

More

Site

© 2026 Bigland Network. All rights reserved.Always test commands on a non-production system first.
Scroll to Top