I’ve noticed in our project the following use of a Common Table Expression to perform a simple select from a view:
WITH CTE_View_Alias AS
(
SELECT
Id,
Column1,
Column2
FROM VW_View
),
CTE_Foo AS
(
SELECT
B.Bar_Id,
V.Column1
FROM VW_Bar B
INNER JOIN CTE_View_Alias V
ON B.View_Id = V.Id
)
The CTE is only used in one other place, another CTE. The columns in the CTE are a subset of the view’s columns.
Is there a benefit to using this? Why not directly reference the view? Unfortunately, the originator of these sql statements is no longer with the company. To me, this reduces readability but I don’t want to eliminate it if there’s a reason my inexperience prevents me from seeing.
There’s no difference between:
…and:
It’s plausible the view isn’t necessary either, but that’s not the question posed…
There is no performance difference between the previously mentioned options vs a derived table either:
The CTE is syntactic sugar for a derived table, if not using recursive functionality.
Conclusion
You’ll have to ask the author why they chose to use a CTE. It possible there were more complex operations that were removed & the CTE was left as-is in the fear of breaking something unforeseen. Or it’s just functionality they wanted to use…
I always fear that questions like these are too abstracted/simplified to demonstrate decisions.