Why CTE (Common Table Expressions) in some cases slow down queries comparing to temporary tables in SQL Server

后端 未结 3 961
予麋鹿
予麋鹿 2021-02-07 09:56

I have several cases where my complex CTE (Common Table Expressions) are ten times slower than the same queries using the temporary tables in SQL

3条回答
  •  梦如初夏
    2021-02-07 10:32

    There are different use cases for the two, and different advantages/disadvantages.

    Common Table Expressions

    Common Table Expressions should be viewed as expressions, not tables. As expressions, the CTE does not need to be instantiated, so the query optimizer can fold it into the rest of the query, and optimize the combination of the CTE and the rest of the query.

    Temporary Tables

    With temporary tables, the results of the query are stored in a real live table, in the temp database. The query results can then be reused in multiple queries, unlike CTEs, where the CTE, if used in multiple separate queries, would have to be a part of the work plan in each of those separate queries.

    Also, a temporary table can have an index, keys, etc. Adding these to a temp table can be a great assistance in optimizing some queries, and is unavailable in the CTE, though the CTE can utilize the indexes and keys in the tables underlying the CTE.

    If the underlying tables to a CTE don't support the type of optimizations you need, a temp table may be better.

提交回复
热议问题