Is order by clause allowed in a subquery

前端 未结 9 1503
离开以前
离开以前 2020-12-10 14:34

Is there any reason why or why not you should do an \'order by\' in a subquery?

9条回答
  •  北海茫月
    2020-12-10 15:21

    You should use it if the subquery uses some kind of LIMIT / TOP.

    SQL Server will not allow it unless the subquery contains TOP or FOR XML clause as well:

    -- Fails
    WITH    q(id) AS
            (
            SELECT  1
            UNION ALL
            SELECT  2
            )
    SELECT  *
    FROM    (
            SELECT  *
            FROM    q
            ORDER BY
                    id DESC
            ) q2
    
    -- Succeeds
    WITH    q(id) AS
            (
            SELECT  1
            UNION ALL
            SELECT  2
            )
    SELECT  *
    FROM    (
            SELECT  TOP 1 *
            FROM    q
            ORDER BY
                    id DESC
            ) q2
    
    -- Succeeds, but ORDER BY is ignored
    WITH    q(id) AS
            (
            SELECT  1
            UNION ALL
            SELECT  2
            )
    SELECT  *
    FROM    (
            SELECT  TOP 100 PERCENT *
            FROM    q
            ORDER BY
                    id DESC
            ) q2
    

提交回复
热议问题