Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql temp tables @tmp vs #tmp

whats the difference between the two types of temp tables @tmp vs #tmp in SQL 2005? and are their other types i am unaware of?

thanks

like image 404
kacalapy Avatar asked Nov 04 '10 20:11

kacalapy


People also ask

What are the two main types of temporary tables?

SQL Server provides two types of temporary tables according to their scope: Local Temporary Table. Global Temporary Table.

Is it better to use CTE or temp table?

If you are joining multiple tables with millions of rows of records in each, CTE will perform significantly worse than temporary tables. I've seen this from my own experience. CTE's perform significantly slower. CTE's also perform slower because the results are not cached.

Which is faster view or temp table?

The answer lies in performance. It takes processing time to create a view table. If you are going to use the data only once during a database session, then a view will actually perform better than a temporary table because you don't need to create a structure for it.

Which is faster CTE or temp table or table variable?

Looking at SQL Profiler results from these queries (each were run 10 times and averages are below) we can see that the CTE just slightly outperforms both the temporary table and table variable queries when it comes to overall duration.


1 Answers

#tmp is a temp table and acts like a real table mostly. It can have indexes, can have statistics, participates in transactions, optimiser will work out correct row estimates

@tmp is a table variable. No indexes, no statistics, not transaction aware, optimiser always assumes exactly 1 row

Otherwise, they are both scoped (slightly different), in memory/cache but context is tempdb though, will spill to disk if too big etc

Edit:

About keys on table variables. They make no difference. There are no stats and one row is assumed. It will change a table scan to a clustered index scan which is the same. Check any query plan and estimated rows.

Also, just read this Read What a difference a temp table makes over a table variable

The first thing that I did was put a primary key on the @ComputersToProcess table variable. That turned the table scan into a Clustered Index Scan, but didn’t do anything for performance.

like image 57
gbn Avatar answered Sep 30 '22 15:09

gbn