Saturday, November 30, 2013

Benefits and Limitations of Common Table Expression (CTE)

In my previous post, I've written about the basics of CTE. But every feature has its own benefits and limitations. I want to write about them now.

Benefits of CTE


  • CTE can be termed as 'Temporary View' used as a good alternative for a View in some cases.
    • The main advantage over a view is usage of memory. As CTE's scope is limited only to its batch, the memory allocated for it is flushed as soon as its batch is crossed. But once a view is created, it is stored until user drops it. If the view is not used after creation then it's a mere waste of memory.
    • CPU cost for CTE execution is lesser when compared to that of View.
    • Like View, CTE doesn't store any metadata of its definition and provides better readability.
  • A CTE can be referred for multiple times in a query.
  • As the scope is limited to the batch, multiple CTEs can have the same name which a view cannot have.
  • It can be made recursive.

Limitations of CTE

Though using CTE is advantageous, it does have some limitations to be kept in mind,
  • We knew that it is a substitute for a view but a CTE cannot be nested while Views can be nested.
  • View once declared can be used for any number of times but CTE cannot be used. It should be declared every time you want to use it. For this scenario, CTE is not recommended to use as it is a tiring job for user to declare the batches again and again.
  • Between the anchor members there should be operators like UNION, UNION ALL or EXCEPT etc.
  • In Recursive CTEs, you can define many Anchor Members and Recursive Members but all the Anchor Members must be defined before the first Recursive Member. You cannot define an Anchor Member between two Recursive Member.
  • The number of columns, the data types used in Anchor and Recursive Members should be same.
  • In Recursive Member, aggregate functions like TOP, operator like DISTINCT, clause like HAVING and GROUP BY, Sub-queries, joins like Left Outer or Right Outer or Full Outer are not allowed. Regarding Joins, only Inner Join is allowed in Recursive Member.
  • Recursion Limit is 32767, crossing which results in the crash of server due to infinite loop.

Regarding this topic, Microsoft provided a very good documentation. 

No comments:

Post a Comment