SQL Server T-SQL Window Functions Tutorial
By: Koen Verbeeck
Window functions are a specific subset of functions in T-SQL – the dialect of the SQL language Microsoft uses in their database product Microsoft SQL Server – allowing you to create more complex queries. Their application ranges from statistical queries, calculating subtotals, helping you identify duplicate rows, to solving well known problems such as the gaps and islands problem.
With window functions, you can solve some problems in T-SQL more elegantly than before. In a few cases, it allows you to write a set-based query to solve your issue, instead of resorting to a cursor, which is in most cases a slower alternative.
In this tutorial, we’ll give you an introduction to the concepts and usage of the window functions. Learning about these functions and applying them in your everyday programming will make you write better and more efficient T-SQL.
After some introduction work, we’ll go over some of the different categories of window functions. The high-level outline is as follows:
- Some examples with a couple of use cases
- Introduction to window functions
- Aggregate functions
- The ROW_NUMBER function
- Ranking functions
- Get access to other rows with LAG and LEAD and other offset functions
- Statistical functions
- Improving performance
- The Gaps and Islands problem
You can use the outline on the left to browse the tutorial or use the arrows “Previous” and “Next”.
- There are some very good reference books about window functions in T-SQL:
- Microsoft SQL Server 2012 High-Performance T-SQL Using Window Functions by Itzik Ben-Gan. This is one of my personal favorite technical books. It’s short and to the point. Although it mentions SQL Server 2012 in the title (when most of the window functions were introduced), it is still very accurate.
- Expert T-SQL Window Functions in SQL Server by Kathi Kellenberger.