Is there any performance gain using 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.
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.
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.
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.
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.
From what I have read and my limited use of them, no, they are just easier to read and can reference themselves.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With