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.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot facebook Lessthandot rss

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

How To Use ROW NUMBER() In A WHERE Clause

From Wiki

Jump to: navigation, search

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


  1. USE AdventureWorks
  2. GO
  3.  
  4. SELECT
  5. ROW_NUMBER() OVER (ORDER BY addressline1) AS rowNum,
  6. addressline1,
  7. city
  8. FROM person.address
  9. 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

  1. SELECT * FROM ( SELECT
  2. ROW_NUMBER() OVER (ORDER BY addressline1) AS rowNum,
  3. addressline1,
  4. city
  5. FROM person.address) AS x
  6. WHERE rowNum > 3;


--CTE

  1. WITH x (rowNum,addressline1,
  2. city) AS
  3. (SELECT
  4. ROW_NUMBER() OVER (ORDER BY addressline1) AS rowNum,
  5. addressline1,
  6. city
  7. FROM person.address)
  8.  
  9. SELECT * FROM X
  10. WHERE rowNum > 3;



Contributed by: --SQLDenis 02:34, 31 May 2008 (GMT)

Part of SQL Server Programming Hacks

Section Sorting, Limiting

284 Rating: 2.9/5 (127 votes cast)