How to create temp table using Create statement in SQL Server?

40    Asked by priya_3866 in SQL Server , Asked on May 25, 2025

How can you create a temporary table using the CREATE statement in SQL Server? What syntax should you follow, and when is it useful to use temp tables in your queries?

Answered by Larry McLeod

Creating a temporary table using the CREATE statement in SQL Server is quite handy when you need to store and manipulate intermediate results without affecting your main database tables. But how exactly do you do it, and what are the best practices?

In SQL Server, temporary tables are created in the tempdb database and exist only for the duration of your session or procedure. You can create them using the standard CREATE TABLE statement, with just a small tweak.

Here’s how to create a temporary table:

Use a single # before the table name to create a local temporary table:

CREATE TABLE #TempEmployees (
    ID INT,
    Name NVARCHAR(100),
    Department NVARCHAR(50)
);

This table will only be accessible in your current session.

Use double ## to create a global temporary table, which is accessible across multiple sessions:

CREATE TABLE ##GlobalTemp (
    ID INT,
    Value VARCHAR(50)
);

Key Points to Remember:

  • Temp tables are automatically dropped when the session ends (for local) or when all sessions using the global table are closed.
  • You can insert data into them just like regular tables.
  • They’re great for breaking down complex queries, especially in stored procedures.

Using temporary tables can help improve performance and make your queries more readable and modular. Just make sure you clean them up if needed and avoid name conflicts with other temp tables in shared environments.



Your Answer

Interviews

Parent Categories