Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
How To Use ROW NUMBER() In A WHERE Clause
From Wiki
If you try to use the ROW_NUMBER() windowing function in a WHERE clause you will get an error. Run the code below to see what I mean
- USE AdventureWorks
- GO
- SELECT
- ROW_NUMBER() OVER (ORDER BY addressline1) AS rowNum,
- addressline1,
- city
- FROM person.address
- WHERE rowNum > 3;
That gave the following error Server: Msg 207, Level 16, State 1, Line 6 Invalid column name 'rowNum'.
What you have to do is use Common Table Expressions or use a subquery. Below are both methods.
--Subquery
- SELECT * FROM ( SELECT
- ROW_NUMBER() OVER (ORDER BY addressline1) AS rowNum,
- addressline1,
- city
- FROM person.address) AS x
- WHERE rowNum > 3;
--CTE
- WITH x (rowNum,addressline1,
- city) AS
- (SELECT
- ROW_NUMBER() OVER (ORDER BY addressline1) AS rowNum,
- addressline1,
- city
- FROM person.address)
- SELECT * FROM X
- WHERE rowNum > 3;
Contributed by: --SQLDenis 02:34, 31 May 2008 (GMT)
Part of SQL Server Programming Hacks
Section Sorting, Limiting



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.