Explain Codes LogoExplain Codes Logo

Is it necessary to use # for creating temp tables in SQL server?

sql
temp-tables
table-variables
sql-performance
Alex KataevbyAlex Kataev·Dec 22, 2024
TLDR

In SQL Server, local temp tables are prefixed with a single # and exist solely within the scope of the current session. They disappear when the session ends. To create a global temp table that's accessible across multiple sessions, lead the name with a **double

##**. These persist until no active sessions are referencing them. Omit the hash for permanent tables which endure persistently within the database.

Local Temp Table Example:

-- sing a song with me “# I got temp problems, but a SQL ain’t one" CREATE TABLE #LocalTemp (ID int);

Global Temp Table Example:

-- If global warming is real, why does this table even exist? CREATE TABLE ##GlobalTemp (ID int);

For simple operations or small data sets, it might be suitable to utilize the efficient table variables. They come into their own when dealing with less than 5000 rows and excluding complex operations, like indexes or complex transactions.

Assessing temp tables vs. table variables

To choose between temporary tables and table variables, workload size and operation complexity should be considered. Temporary tables shine when you foresee the need for indexes, complex queries, or transaction rollbacks.

Conversely, table variables suit smaller data sets, simplifying transaction log management and potentially boosting performance, when complex features of temporary tables are not required.

Insights on table storage

Be it temporary tables or table variables, both kinds reside within the tempdb database. Neither is directly stored in RAM, refuting a common myth. Their performance is largely contingent on the indexing, workload, and locking behaviors.

Best practices for temporary table usage

To make the most of temporary tables, here are some pointers:

  • Indexes: Like in a permanent table, indexes can be created on temp tables to speed up queries.
  • Row estimation: For larger datasets, table statistics may become outdated. Use hints like RECOMPILE to ensure the SQL Server’s query optimizer uses accurate row counts.
  • Cleanup: Always drop temporary tables in stored procedures or scripts to promptly free up resources.

Exploring in-depth details

For more intricate applications, check out the definitive resources on temporary tables and table variables to exploit their functionality and performance aspects.