SQL Row_Number() function in Where Clause

后端 未结 10 1525
野性不改
野性不改 2020-12-02 16:11

I found one question answered with the Row_Number() function in the where clause. When I tried one query, I was getting the following error:

10条回答
  •  旧时难觅i
    2020-12-02 16:49

    In response to comments on rexem's answer, with respect to whether a an inline view or CTE would be faster I recast the queries to use a table I, and everyone, had available: sys.objects.

    WITH object_rows AS (
        SELECT object_id, 
            ROW_NUMBER() OVER ( ORDER BY object_id) RN
        FROM sys.objects)
    SELECT object_id
    FROM object_rows
    WHERE RN > 1
    
    SELECT object_id
    FROM (SELECT object_id, 
            ROW_NUMBER() OVER ( ORDER BY object_id) RN
        FROM sys.objects) T
    WHERE RN > 1
    

    The query plans produced were exactly the same. I would expect in all cases, the query optimizer would come up with the same plan, at least in simple replacement of CTE with inline view or vice versa.

    Of course, try your own queries on your own system to see if there is a difference.

    Also, row_number() in the where clause is a common error in answers given on Stack Overflow. Logicaly row_number() is not available until the select clause is processed. People forget that and when they answer without testing the answer, the answer is sometimes wrong. (A charge I have myself been guilty of.)

提交回复
热议问题