You are on page 1of 21

Ho me Guest bo o k D i scl ai mer Sear ch

T ECH  A HEAD Feeds:   Posts   Comments

feel t he p as s ion of t echnologies  here!

.NET – Basic Terms in .Net »

SQL – Temporary Tables

September 27, 2007 by Prashant Pandey

Temporary Tables are a great T-SQL feature that lets you store and process intermediate
results by using the same selection, update, and join capabilities that you can use with
typical SQL Server tables.

open in browser customize free license contest

typical SQL Server tables.
“In the early days when I used Access I used to create tables that I treated as temporary
and then delete them whenever I finished my task ”. Using SQL Server this is much

Types of Temporary Tables in SQL

You can create two types of temporary tables in SQL, local and global temporary tables.
The two types of temporary tables, local and global, differ from each other in their names,
their visibility, and their availability.
Local Tem porary Tables

Local temporary tables prefix with single number sign (#) as the first character of
their names, like (#table_name).
Local temporary tables are visible only in the current session OR you can say that BLOG VISITORS
they are visible only to the current connection for the user. 198,618 visitors
They are deleted when the user disconnects from instances of Microsoft SQL
Global Tem porary Tables .NET (4)
Global temporary tables prefix with double number sign (##) as the first character
C SS (1)
of their names, like (##table_name).
Firefox (1)
Global temporary tables are visible to all sessions OR you can say that they are
Fun (2)
visible to any user after they are created.
Google C hrome (1)
They are deleted when all users referencing the table disconnect from Microsoft
Interview Questions (1)
SQL Server.
JavaScript (1)
For example: MySQL (1)
If you create a table named employees, the table can be used by any person who has the Poll (1)
security permissions in the database to use it, until the table is deleted. If you create a SQL (6)
local temporary table named #employees, you are the only person who can work with the
table, and it is deleted when you disconnect. If you create a global temporary table named
open in browser customize free license contest
table, and it is deleted when you disconnect. If you create a global temporary table named
##employees, any user in the database can work with this table. If no other user works
with this table after you create it, the table is deleted when you disconnect. If another user
works with the table after you create it, SQL Server deletes it when both of you
disconnect. SQL statements for creating the temporary table using the CREATE TABLE


SELECT * FROM #MyTempTable  Active visitor

When you create local or global temporary tables, the CREATE TABLE syntax supports
constraint definitions with the exception of FOREIGN KEY constraints. If a FOREIGN ARCHIVES
KEY constraint is specified in a temporary table, the statement returns a warning
October 2010 (1)
message indicating that the constraint was sk ipped, and the table is still created without
February 2010 (2)
the FOREIGN KEY constraints. Temporary tables cannot be referenced in FOREIGN
August 2009 (1)
KEY constraints.
July 2009 (1)
June 2009 (2)
Naming Of Temporary Tables September 2008 (3)
Temporary tables are always created in tempdb. No matters it is created from the stored
April 2008 (2)
procedure internally or from the SQL Query Analyzer window. If a local temporary table is
March 2008 (2)
created in a stored procedure or application that can be executed at the same time by
December 2007 (1)
several users, SQL Server has to be able to distinguish the tables created by the different
November 2007 (1)
users. SQL Server does this by internally appending a numeric suffix to each local
October 2007 (7)
temporary table name. The full name of a temporary table as stored in the sysobjects
September 2007 (2)
table in tempdb consists of table name specified in the CREATE TABLE statement and
the system-generated numeric suffix. To allow for the suffix, table_name specified for a
local temporary name cannot exceed 116 characters. CATEGORY CLOUD
Reason: .NET
“Table names in SQL are the combination of owner.table_name and it must be unique
within the database. Table_name can contain a maximum of 128 characters, except for
Firefox   Fun   Google C hrome
open in browser customize free license contest
Firefox   Fun   Google C hrome
local temporary table names (names prefixed with a single number sign (#)) that cannot
Interview Questions
exceed 116 characters.” For example:
JavaScript   MySQL   Poll

CREATE TABLE #Yaks (YakID int,YakName char(30))
SELECT Name FROM tempdb.dbo.sysobjects WHERE Name LIKE ‘#yak%’ The above
select query will return the result something like below displayed. name
——————————————————————- TOP POSTS
#Yaks__________________________________________________00000000001D (1
SQL - Temporary Tables
row(s) affected)
SQL - Derived Tables
SQL Server stores temporary tables as a database object with a type of unique number ASP.NET - Server.Transfer
appended on the end of the name. But in case of temporary tables it may be the v/s Response.Redirect
possibility that two users can create the temporary table with the same name as we know ASP.NET - Server.Transfer
that all temporary tables stored in the tempdb database, so if the name of both temporary v/s Server.Execute
tables will be same then SQL server will through an error to the user because objects ASP.NET - Using "radio
name in the SQL server must be unique in the database. So, to avoid this problem button" inside grid view
whenever anyone creates any temporary table SQL server automatically appends a unique
string with the table name that is given by user while creating the table, But don’t worry
you need to do anything with this extra string, It does all this for you automatically. You
just have to refer to your #table_name with which you have created the temporary table. MySQL: How to reset

You can refer this name anywhere in your code where you want. AUTO_INC REMENT value of
a table
Poll: What is Your
Deletion of Temporary Tables Preferred Browser?

A local temporary table created in a stored procedure is dropped automatically ASP.NET – Function to Fill

when the stored procedure completes. The table can be referenced by any nested Month, Date and Year

stored procedures executed by the stored procedure that created the table. The Dropdown lists

table cannot be referenced by the process which called the stored procedure that .NET – Translate color in .net

created the table. from HTML colors

Google C hrome –
All other local temporary tables are dropped automatically at the end of the StumbleUpon submit and
current session.
open in browser customize free license contest
current session. stumbling buttons

Global temporary tables are automatically dropped when the session that created
the table ends and all other tasks have stopped referencing them. The association RECENT COMMENTS
between a task and a table is maintained only for the life of a single Transact-SQL Khaleek on ASP.NET
statement. This means that a global temporary table is dropped at the completion – Server.Transfe…
of the last Transact-SQL statement that was actively referencing the table when
the creating session ended. Khaleek on ASP.NET
– Server.Transfe…
For example:
Doan Hanh on
SQL statements for deleting the temporary table using the DROP TABLE statement:
DROP TABLE #Table_name A local temporary table created within a stored procedure or
trigger is distinct from a temporary table with the same name created before the stored
procedure or trigger is called.

Use of Temporary Table
Temporary tables are used in several ways. Most commonly uses 12,657
spam comments
to keep the result of a called stored procedure,

to reduce the number of rows for joins,

to aggregate data from different sources, or

to replaces cursors and for parameterized views.

SQL Server cursors have huge overhead. Maintenance of code is much easier if you use
temporary tables to the T-SQL. It will be much easier to debug your stored procedure
when your using temporary tables as the data will be saved in temporary tables.

Limitations of Temporary Tables

Temporary tables are created in the tempdb database and create additional overhead for
open in browser customize free license contest
SQL Server, reducing overall performances. This happens because all reads and writes to
the temporary tables are done within the tempdb database.

Using Temporary Tables Effectively

If you do not have any option other than to use temporary tables, use them effectively.
There are few steps to be taken.

Only include the necessary columns and rows rather than using all the columns
and all the data which will not make sense of using temporary tables. Always filter
your data into the temporary tables.

When creating temporary tables, do not use SELECT INTO statements, as it

places locks on system objects. Instead of SELECT INTO statements, create the
table using Transact-SQL DDL statements and use INSERT INTO to populate the
temporary table.

Use indexes on temporary tables. Earlier days, I always forget to use an index on
temporary. Specially, for large temporary tables consider using clustered and non-
clustered indexes on temporary tables. You will have to test to see if indexes help
or hurt overall performance.

After you finish the using your temporary table, delete them. This will free the
tempdb resources. Yes, I agree that temporary tables are deleted when
connection is ended. But do not wait until such time.

When creating a temporary table do not create them with a transaction. If you
create it with a transaction, it will lock some system tables (syscolumns,
sysindexes, syscomments). This will prevent others from executing the same

In general, temp tables should be avoided, if possible. Because they are created in the
tempdb database, they will create additional overhead for SQL Server, slowing overall
open in browser customize free license contest
performance. As an alternative to temp tables, consider the following alternatives:

Rewrite your code so that the action you need completed can be done using a
standard query or stored procedure, without using a temp table.

Use a derived table.

Consider using a correlated sub-query.

Use a permanent table instead.

Use a UNION statement to mimic a temp table.

Use a table variable.

It all depends on your requirement at that time when you are creating your query, but as
written in Microsoft SQL Server Book Online,
“Consider using table variables instead of temporary tables. Temporary tables are useful in
cases when indexes need to be created explicitly on them, or when the table values need
to be visible across multiple stored procedures or functions. In general, table variables
contribute to more efficient query processing.”

If you are using SQL Server 2000 or higher, you can take advantage of the new TABLE
variable type. These are similar to temporary tables except with more flexibility and they
always stay in memory.
The code using a table variable might look like below:

DECLARE @TibetanYaks TABLE (
YakID int,
YakName char(30) )

INSERT INTO @TibetanYaks (YakID, YakName)


open in browser customize free license contest
FROM dbo.Yaks WHERE YakType = ‘Tibetan’

Table variables don’t need to be dropped when you are done with them.

Which to use
If you have less than 100 rows generally use a table variable. Otherwise use a
temporary table. This is because SQL Server won’t create statistics on table

If you need to create indexes on it then you must use a temporary table.

When using temporary tables always create them and create any indexes and
then use them. This will help reduce recompilations. The impact of this is reduced
starting in SQL Server 2005 but it’s still a good idea.

Generally, temporary tables should be avoided as much as possible. If you need to use
them follow the steps above so that you have the minimum impact on server performance.


Reference from and many thanks to following websites and articles:

Microsoft’s Book Online For SQL Server 2000
Sql Server Central
Prashant Pandey (TechAhead)
  2 Votes 

open in browser customize free license contest

Ads by Google
Washington DC Coupons
1 ridiculously huge coupon a day. It's like doing DC at 90%

Posted in SQL | 28 C omments

Like Be the first to like this post.

28 Responses
Rohan Patil on October 1, 2007 at 5:43 pm | Reply

This is very usefull information for all computer users n
programmers.Prashant Rocks!!!

mannu4mit on October 16, 2007 at 1:08 pm | Reply

u are doing a gr8 work.
this one is useful place for all developers searching for latest .net/sql
interview questions.
even for the beginners who want to grassp knowledge…

Best of luck dude…
continue with this good work.

Amit ………………..
open in browser customize free license contest
rahul on October 30, 2007 at 12:04 pm | Reply

it helped me very much

prashantvictory on October 30, 2007 at 5:42 pm | Reply

Hi rahul, thanks for your comment.. and tell you one thing .. good
comments always boost my confidence.. but bad comments or
suggestion are also invited caz they told me to make myself more
perfect in that area..
I pleased that this article helps you, So keep visiting the blog for new and
intresting topics.. 

Uday on October 31, 2007 at 5:33 am | Reply

Thank u very much for giving this much information.But will u add a little
bit more about this

prashantvictory on October 31, 2007 at 5:56 am | Reply

Hi Uday,
I think i covered all about temporary tables , wht i think… But as you
know no one is perfect,
so tell me wht else i need to add in this article. tell me i’ll add it here,
Your suggestions are always welcome…

open in browser customize free license contest

Ravi on November 26, 2007 at 7:23 pm | Reply

Hi Prashant,
Great work dude.Do more and more better next best wishes
are always with u.
Ravi Raghav

Ravi on November 26, 2007 at 7:31 pm | Reply

Real IT services specialises in providing Web and Software
Development solutions in terms of the requirements like IT
Outsourcing,CRM,Business Process Outsourcing,Content Management
System,Offshore Software Development,Website Promotion(SEO),Customer
Software Development at an affordable cost with 100% customer satisfaction.To
know more about our services
Go here

bhanu on February 27, 2008 at 12:16 pm | Reply

i need to have questionnumber as an identity (int)
in which my sp contains one parameter
like this
CREATE PROCEDURE spGetAnswerDescription1(@TestId int)
create table #temptable
(QID int identity,
QuestionID int)
open in browser customize free license contest
QuestionID int)
tbAnswers.AnswerDescription,tbQuestionPaper.ImagePath from
tbQuestionPaper ,tbAnswers

where tbQuestionPaper.QuestionId=tbAnswers.QuestionId and

select * from #temptable


when dis compiled i m getting an error tht i cant insert when identity_insert is
when i create SP with no parameters its working accrately
plzz send me the solution

steve on March 17, 2008 at 11:48 pm | Reply

Great detail.

Is there ever a possibility of “name collision”, if the *same* user runs
the same SP and two instances of the temp table are in existence at the same

Stored proc is being executed from a web app, if that means anything.

Thank you,


Prashant Pandey on March 18, 2008 at 4:29 pm | Reply

open in browser customize free license contest

Hi steve,
its nice to hear that you like this article.

“Is there ever a possibility of “name collision”, if the *same* user runs the same
SP and two instances of the temp table are in existence at the same time?

Stored proc is being executed from a web app, if that means anything.“

Now what i think is “yes there may be a possibility of name collision” i am not
sure caz you are executing the SP from different web applications, but again the
point is your sql server is same. So it may be arround 80% chances of name
But to avoid this what you can do is DROP the temporary table from your sp
using the following code
DROP TABLE #my_temp

So there will be very minor possibilities of name collison.

I’m discussing your topic further with some experts, so if will find anything
special will let you know here.

keep visiting the blog.

steve on March 18, 2008 at 4:46 pm | Reply

Thanks Prashant. Because of the way the web app is designed, it is
improbable that the same user will run the same SP simultaneously, but
because the SP will get relatively heavy use it is possible, so I
appreciate your follow up.

The #temp table however will have very few (less than 10 rows) so it’s lifetime
should be quick and short.

open in browser customize free license contest

Thanks again,


Prashant Pandey on March 18, 2008 at 5:00 pm | Reply

Thanks for your appreciation.
I said that there are chances of name collision because suppose if you
have a sp which creates a temp table and use that, but remember its
not deleting that table.
So in query analyzer window if you execute this sp twice then in the 2nd time
you’ll get an error something like “#temp_table already exists” So by
considering this point in the case of web app, there may be a possibilities of
name collision, because all the queries executing in the same SQL server.
but as you said there are very few chances, but still there is 1% chance, So i
thinks its better to drop temp tables if not used in any further query, because if
u not delete these they will unnecessarily take the space in the SQL Server.


km0ti0n on April 10, 2008 at 11:05 am | Reply

Thank you for you detailed example.

I need to take the example above one step further.

For Example, if I make a temporary table I then want to innerJoin this temp
table to another table to retunr rows form the joined table.

This is my statment :


open in browser customize free license contest





If I remove the end from “INNER JOIN” it works fine, but this errors with a error :

“Must declare the variable ‘@THEIDS’.”

Note the Group By Clause this is why I’ve had to create a temp table.

Id it possible to create a temp table and then use it like this?

CHIN on May 15, 2008 at 11:52 am | Reply

This is very usefull and clearfull article ever than others.
thanks for it…


vaibhav on August 6, 2008 at 7:50 am | Reply

Its really good infromation abt tempory tables gives clear cut idea abt
Thanks lot!!!!!!!!!!!!!

open in browser customize free license contest

gyan shukla on August 11, 2008 at 6:55 am | Reply

thanks alot……… these are great information regarding to temporary
tables…and really help to understand DB query optimization

Praveen Krishna R on September 19, 2008 at 2:52 pm | Reply

Thank You, for this Detailed Guideline.

Rahul Wadekar on November 30, 2008 at 12:40 pm | Reply

Good Job…Thanks

Prabhat Dubey on December 18, 2008 at 10:51 am | Reply


I have a query regarding the nested SP’s and use of Global Temp Table
in it.
The thing is I am calling SP2(lets say) from Sp1. This Sp2 is fetching multiple
records from a table and these records needs to be sent back to SP1.
Now the problem here is can I define a GTT in SP1 and insert data in it in SP2
and again retrieve it in SP1.
If so can someone tell me how and what will be the syntax..
This is really a showstopper for me?

Immediate response is highly appreciated.

Vishal on January 22, 2009 at 3:50 pm | Reply
open in browser customize free license contest
Hi Prashant,
You are doing a great job. The article is really very good.
I have a question. I have a stored procedure in which at the end of the
stored procedure after all the necessary code is written the global temporary
tables are dropped. Once the stored procedure is executed how do i view the
data in the temporary tables to troubleshoot the errors. I was told to comment
on the code where the global temporary tables are dropped, I commented it but
I am unable to save the stored procedure with the changes as it already exists
and could not accomplish my goal. So how do i view the data generated in the
temporary table.

Any suggestions would be of great help.


Alexwebmaster on March 3, 2009 at 10:58 am | Reply

Hello webmaster
I would like to share with you a link to your site
write me here

How to Get Six Pack Fast on April 15, 2009 at 3:11 pm | Reply

This is very up-to-date info. I’ll share it on Twitter.

tk on June 17, 2009 at 1:45 pm | Reply

Hi Prashant,

open in browser customize free license contest

Do you still check these comments? If so, here is my question re the
need for a temp table/table variable.

1) I want to get a result set of job numbers, maybe 20 of them.

2) Then–for each of those jobs–I want to append each job into a parent table,
then retrieve it’s @@IDENTITY.

3) Then–for each job–using it’s @@IDENTITY, I want to append child records for
that job into another table.

The way I’ve come up with is to retrieve my result set into a table variable, then
a cursor to fetch each record, then do the appends for each record.

I could write a loop on the client and call the sproc 20 separate times by
passing the job, but that seems inefficient.

Is there a better way to do this than the idea I had?


Prashant Pandey on June 17, 2009 at 5:29 pm | Reply

Hi @tk,

I think you, first fetch the job numbers data and run a while loop on
this job_number data and insert parent records.

After that in the same loop fetch the PARENT ID from parent table on the
basis of Job_number, and run another while loop on that data. if the job
number is not present then you need to go with @@IDENTITY (but if the job
number is not present I think you should check you’re database structure
again for implementing proper relationships in between tables, so that
fetching and insertion can be easy and faster)

open in browser customize free license contest

WHILE LOOP is there in SQL and they are better in all aspects than

Always prefer WHILE loops over CURSORS, both performs the same kind of
functionality, whereas CURSORS are slow.

Checkout this article:
cursors/ in this I have tried my best to explain WHY cursors are slow and
how to use WHILE loop as an alternative for CURSORS 

swat on July 6, 2009 at 12:22 pm | Reply

I have a stored proc A, which creates a temporary table. Inside this
stored proc, I have another stored proc B where I am inserting the
values into the temp table. After the completion of stored proc B, I am
doing a select *from #temptable in proc A. Since I have created the temp table
in proc A, I shouldnt have any problems while doing a select query. Am I correct

kalpesh on July 2, 2010 at 2:48 am | Reply

we can use CTE(common table expression also insted of temp

Muneer on December 14, 2010 at 8:01 am | Reply

very usefull article

open in browser customize free license contest

Comments RSS

Leave a Reply

Your email address will not be published. Required fields are marked  *

Nam e   *

Em ail  *

W e bsite

Post Comment

 Notify me of follow-up comments via email.
open in browser customize free license contest
 Subscribe by email to this site

Blog at Theme: MistyLook by Sadish.

open in browser customize free license contest