peakit peakit - 2 months ago 13
SQL Question

How tempDB works?

I am trying to understand the

tempDB
and following are the doubts popping in my mind.


  1. What is the lifetime of data in
    tempDB
    ? Say a query is doing some
    Order By
    and uses
    tempDB
    for performing that. After this query finishes, someone else also executes a query which utilizes the
    tempDB
    . Will the second query find records written by first query in the
    tempDB
    or will they be deleted?

  2. Are there any visible tables created inside the
    tempDB
    by the Sql Engine? How can I know which temporary table is created because of this query? Is there any naming convention followed by the Sql engine for naming these temporary tables?



I am new to
tempDB
so please pardon me for asking such silly (if at all) questions :-)

It will be very nice if someone can point me to a good resource which can help me learn about tempDB.

Answer

Temp table is stored in tempdb until the connection is dropped (or in the case of a global temp tables when the last connection using it is dropped). You can also (and it is a good practice to do so) manually drop the table when you are finished using it with a drop table statement.

No, others cannot see your temp tables if they are local temp tables (They can see and use global temp tables) Multiple people can run commands which use the same temp table name but they will not be overlapping in a local temp table and so you can have a table named #test and so can 10,000 other users, but each one has its own structure and data.

You don't want to generally look up temp tables in tempdb. It is possible to check for existence, but that is the only time I have ever referenced tempdb directly. Simply use your temp table name. Example below of checking for existence

  IF OBJECT_ID('TempDB.dbo.#DuplicateAssignments') IS NOT NULL 
  BEGIN 
  DROP TABLE #DuplicateAssignments 
  END  

You name temp tables by prefacing the name with # (for local tables the ones you would use 999.9% of the time) and ## for global temp tables, then the rest of the name you want.