EnjoY | Database Research And Development: SQL Server : Difference between Temp Table and Common Table Expression (CTE)

Wednesday, September 2, 2020

SQL Server : Difference between Temp Table and Common Table Expression (CTE)

 

In this post, I am sharing the important difference between Temp Table and Common Table Expression (CTE) of the SQL Server.
I recently wrote an article on the difference between Temp Table and Table Variable of the SQL Server.


The theory and practice of Temp Table, Table Variable and CTE is one of my favourite topics of the SQL Server.

A CTE is used for a temporary result set that is defined within the execution scope of the query.
A Temp Table is also used for a temporary result set, but it can be defined for limited execution scope or can be used to define for global execution scope as a Global Temp Table.

A CTE is substituted for a view when the general use of a view is not required, and you do not have to store the definition of metadata.

CTE always uses memory and Temp Table stored in the TempDB.

The Scope of CTE is only for the query and can be referenced multiple times in other CTEs.
The child objects also access the Temp Table, and it persists until the end of the sessions.

We can not use NOLOCK and other isolation levels with CTE and with the Temp Table, we can apply it explicitly.

If we require to CTE for another batch query, it requires recreation of it.
The Temp Table can be used for all batches of a session.

A CTE doesn’t maintain any statistics and any metadata information, Temp table is maintaining a require statistics.

A CTE is a never part of the transaction and locking and its treated as system transaction.
The temp table operations are a part of user transactions.

If we have a large dataset, we should use Temp Table and with the small dataset, we can use CTE very effectively.

No comments:

Post a Comment

It’s all about friendly conversation here at small review :) I’d love to be hear your thoughts!

Be sure to check back again because I do make every effort to reply to your comments here.

Featured Post

SQL Server : SELECT all columns to be good or bad in database system

This article is half-done without your Comment! *** Please share your thoughts via Comment *** In this post, I am going to write about one o...

Popular Posts