Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Performance: derived table vs. common table expression (CTE)

Is there any performance gain using a CTE over a derived table?

like image 685
D.S. Avatar asked Nov 20 '08 19:11

D.S.


People also ask

What is the advantage of a CTE over a derived table?

Derived tables are subqueries that are used in the FROM clause instead of named tables. I like using CTEs over derived tables because CTEs are so much easier to read. Derived tables can be nested and often are several layers deep, becoming difficult to read and understand.

Does CTE in SQL improve performance?

Below is the T-SQL for each of our test query types. Looking at SQL Profiler results from these queries (each were run 10 times and averages are below) we can see that the CTE just slightly outperforms both the temporary table and table variable queries when it comes to overall duration.

Which is better in performance CTE vs temp table?

CTE has its uses - when data in the CTE is small and there is strong readability improvement as with the case in recursive tables. However, its performance is certainly no better than table variables and when one is dealing with very large tables, temporary tables significantly outperform CTE.

Why would you use a common table expression CTE?

CTEs, like database views and derived tables, enable users to more easily write and maintain complex queries via increased readability and simplification. This reduction in complexity is achieved by deconstructing ordinarily complex queries into simple blocks to be used, and reused if necessary, in rewriting the query.


2 Answers

I've used CTEs a lot and it does actually appear to run faster in some scenarios. The server was fairly well loaded, the variation in times on runs was pretty significant, and I can't believe the execution plan was that different, but it still seemed like the ones with the CTE performed better.

like image 193
Cade Roux Avatar answered Sep 20 '22 23:09

Cade Roux


From what I have read and my limited use of them, no, they are just easier to read and can reference themselves.

like image 31
Potbelly Programmer Avatar answered Sep 21 '22 23:09

Potbelly Programmer