9

Why does it say 'Invalid Column Name' for the RowNumber in WHERE.

SELECT Id, Name,
ROW_NUMBER() OVER (ORDER BY Id) AS 'RowNumber'
FROM Folks
WHERE RowNumber=3

While can be used with ORDER BY

SELECT Id, Name
ROW_NUMBER() OVER (ORDER BY Id) AS 'RowNumber'
FROM Folks
ORDER BY RowNumber DESC
Jude
  • 2,353
  • 10
  • 46
  • 70

2 Answers2

9

Try this:

SELECT  *
FROM    (SELECT Id, Name,
                ROW_NUMBER() OVER (ORDER BY Id) AS 'RowNumber'
         FROM    Folks
        ) AS A
WHERE   RowNumber = 3
Jesuraja
  • 3,774
  • 4
  • 24
  • 48
8

You are missing a comma:

SELECT f.*
FROM (SELECT Id, Name,
---------------------^
             ROW_NUMBER() OVER (ORDER BY Id) AS RowNumber
      FROM Folks f
     ) f
WHERE RowNumber = 3;

Plus you cannot use a column alias in a where clause at the same level. A subquery or CTE solves that problem.

And, it is best not to use single quotes for column aliases. You should use single quotes only for string and date constants. In this case, rownumber doesn't need to be escaped at all.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • 1
    _you cannot use a column alias in a where clause at the same level_ Thank you, this is one of those dumb things I should have known and forgot. – coderMe Dec 14 '18 at 15:48