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

In this post, I am sharing important difference between Temp Table and Common Table Expression (CTE) of the SQL Server.

I have recently written one article on the difference between Temp Table and Table Variable of the SQL Server.
You can visit this article here:

The theory and practice of Temp Table, Table Variable and CTE is one of the 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 and it persists before the next query run.
The Temp Table is also accessed by the child objects and it persists till end of the sessions.

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

If we require to CTE for another batch query, it requires to recreate.
The Temp Table can be create and drop explicitly.

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

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

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

Please share your ideas and opinions about this topic with me, your contribution will add true value to this topic.
If anyone has doubts on this topic then please do let me know by leaving comments or send me an email.

If you like this post, then please share it with others.
Please follow dbrnd.com, I will share my experience towards the success of Database Research and Development Activity.

I put up a post every day, please keep reading and learning.
Discover Yourself, Happy Blogging !
Anvesh M. Patel.

More from dbrnd.com

Leave a Reply

2 Comments on "SQL Server: Difference between Temp Table and Common Table Expression (CTE)"

Notify of

Sort by:   newest | oldest | most voted
8 months 6 days ago

Some genuinely fantastic info , Gladiolus I discovered this.

4 months 7 days ago

Hi Anvesh Patel,
Very useful one. looking forward to read more articles in future.