As shown in Using Common Table Expressions on MSDN, you can define a CTE as:
WITH expression_name [ ( column_name [,...n] ) ]
AS
( CTE_query_definition )
and use it like:
SELECT <column_list> FROM expression_name;
Let's say I have following 2 CTEs
with cte1 as(
select name from Table1
)
with cte2(name) as(
select name from Table1
)
A query outputs the same results for both CTEs as the inner query is same. The only difference between these two is that cte2 has column name((name)) defined in its declaration.
When I execute both CTEs, I don't see any difference in the execution plan.
I am just curious to know:
- What difference does it make if I don't specify any column names in CTE definition?
- Why I should/should not specify column names while creating CTE?
- Does it affect query execution plan by any chance? (As far as I have seen, it doesn't make any difference.)