Temporary Table, Table variable or CTE? Which should i use?

All topics about programming / development in T-SQL or other languages for SQL Server.
Post Reply
sgfive
Posts: 14
Joined: Sat Jun 22, 2019 7:04 pm

Sat Jun 29, 2019 10:07 am

Hi, As the subject states, when should i be using a Temporary Table, or a Table Variable or CTE?

Thanks
Tilly
Posts: 8
Joined: Wed Jun 26, 2019 4:49 pm

Sat Jun 29, 2019 10:10 am

Hi,

This all depends on the situation.

Temporary tables

Temporary tables behave like normal tables, but these are created in the TempDB database. They persist until the table has been dropped, or until the connection that created them disappears. They are visible in the procedure that created them and any procedures that that proc calls.

Just like normal tables, they can have primary keys, constraints and indexes, and column statistics are kept for the table.

Temp tables, while they have space assigned to them in the tempDB database, will generally be accessed only from memory, unless the server is under memory pressure, or the amount of data in the table is large.

Table Variables

Table Variables behave very much like other variables in their scoping rules. They are created when they are declared and are dropped when they go out of scope. They cannot be explicitly dropped.

Like with temp tables, table variables reside in TempDB. they have entries in the system tables in tempDB, just like temp tables, and they follow the same behaviour regarding whether they are in memory or on disk.

Table variables can have a primary key, but indexes cannot be created on them, neither are statistics maintained on the columns. This makes table variables less optimal for large numbers of rows, as the optimiser has no way of knowing the number of rows in the table variable.

CTE

Common Table Expressions are more like temporary views than anything else. When you look at the execution plan, you'll see that they are inlined into the query, not materialised and stored. I find, with the exception of recursion, they're more to make queries simpler to write than faster to run.

I hope that helps :)
Post Reply

Social Media