TOP slows down query

前端 未结 3 1933
自闭症患者
自闭症患者 2021-01-21 18:28

I have a pivot query on a table with millions of rows. Running the query normally, it runs in 2 seconds and returns 2983 rows. If I add TOP 1000 to the query it takes 10 secon

3条回答
  •  独厮守ぢ
    2021-01-21 18:57

    There is a specific order in which queries are processed.

    A normal SQL query will be written as follows:

    SELECT [...]
      FROM [table1]
      JOIN [table2]
        ON [condition]
     WHERE [...]
     GROUP BY [...]
    HAVING [...]
     ORDER BY [...]
    

    But the processing order is different:

    FROM [table1]
        ON [condition]
      JOIN [table2]
     WHERE [...]
     GROUP BY [...]
    HAVING [...]
    SELECT [...]
     ORDER BY [...]
    

    When using SELECT DISTINCT [...] or SELECT TOP [...] the processing order will be as follows:

    FROM [table1]
        ON [condition]
      JOIN [table2]
     WHERE [...]
     GROUP BY [...]
    HAVING [...]
    SELECT [...] DISTINCT[...]
    ORDER BY [...]
    TOP [....]
    

    Hence it's taking longer as your SELECT TOP 1000 is processed last.

    Take a look at this link for further details: http://blogs.msdn.com/b/sqlqueryprocessing/

提交回复
热议问题