SQL Row_Number() function in Where Clause SQL Row_Number() function in Where Clause sql sql

SQL Row_Number() function in Where Clause


To get around this issue, wrap your select statement in a CTE, and then you can query against the CTE and use the windowed function's results in the where clause.

WITH MyCte AS (    select   employee_id,             RowNum = row_number() OVER ( order by employee_id )    from     V_EMPLOYEE     ORDER BY Employee_ID)SELECT  employee_idFROM    MyCteWHERE   RowNum > 0


SELECT  employee_idFROM    (        SELECT  employee_id, ROW_NUMBER() OVER (ORDER BY employee_id) AS rn        FROM    V_EMPLOYEE        ) qWHERE   rn > 0ORDER BY        Employee_ID

Note that this filter is redundant: ROW_NUMBER() starts from 1 and is always greater than 0.


Select * from (    Select ROW_NUMBER() OVER ( order by Id) as 'Row_Number', *     from tbl_Contact_Us) as tblWhere tbl.Row_Number = 5