Bear with me, I’m new to intermediate.
My question is – When should I use a CTE? How do I decide if I should use a CTE?
When should I use this:
;with cteTesting as
(
select *
from testing.first_table
)
select *
from testing.second_table s
inner join cteTesting t
on s.key = t.key
Over this:
select *
from testing.second_table s
inner join
(
select *
from testing.first_table
) t
on s.key = t.key
And why? Is this just for code flow, code readability – or is there something more technical? Will one yield better execution plans under some circumstances?
edit: Just realized my example code example is very poor. I was trying to highlight that there are many cases where I can use a select in the from statement instead of a CTE – how do I decide which one I should be using?
For simple examples, it doesn’t make much difference. If you need to use the Recursive features to build up a hierarchy, then you haven’t much choice – you need to use a CTE.
Another case where it probably doesn’t make much performance difference, but does for readability, is when you need to join the same subquery multiple times. If you’re using subqueries, you have to repeat the entire expression, whereas with CTEs, you just use the name twice:
It should also be noted that if you do the above as subqueries, and the expressions are particularly complex, it can sometimes take time for the reader/maintainer to verify that the two subqueries are in fact identical, and there’s not some subtle difference between the two
Also, if you have an indenting style that says that subqueries should appear further to the right than their enclosing query, then expressions that build on other expressions can cause all of the code to shift to the right – whereas with CTEs, you stop and move back to the left in building each subexpression (CTE):
vs: