What are Temp Tables in SQL Server?

Temp tables in SQL Server play a pivotal role in enhancing the efficiency and performance of intricate queries. By dividing complex tasks into smaller, more manageable components and storing interim results in memory, temp tables eliminate redundancies and contribute to a streamlined data retrieval process.

In SQL Server, two types of temp tables, local and global, offer distinct functionalities. Local temp tables, identified with the “#” symbol, are exclusive to the connection that creates them and vanish when the connection closes. Conversely, global temp tables, marked with “##,” persist beyond the connection lifespan and are accessible to any connection.

Let’s jump into the practical aspects of working with temp tables in SQL Server.

Creating a Local Temp Table

To create a local temp table in SQL Server, use the following SQL statement:

-- Create a local temp table called #Chicken 
CREATE TABLE #Chicken ( ID INT, Name VARCHAR(50), Type VARCHAR(50), Price DECIMAL(18,2) );

This table is temporary and will be discarded at the end of the current session.

Inserting Rows into Temp Table

This is an example of Inserting rows into of data into the temp table:

-- Insert four rows of data into the #Chicken table 
INSERT INTO #Chicken (ID, Name, Type, Price) 
VALUES (1, 'Roasted Chicken', 'Whole', 14.99), (2, 'Fried Chicken', 'Wings', 9.99), (3, 'Grilled Chicken', 'Breast', 12.99), (4, 'Teriyaki Chicken', 'Stir Fry', 11.99);

Populating the temp table with relevant data sets the stage for subsequent operations.

Creating an Index on Temp Table

We can improve query performance by adding an index to the temp table:

-- Create an index on the Type column to improve query performance
CREATE INDEX idx_chicken_type ON #Chicken (Type);

Indexes enhance data retrieval speed, especially when querying against specific columns of the temp table.

Selecting from Temp Table

Retrieve data from the temp table simply by running a SELECT statement:

-- Retrieve all rows from the #Chicken table 
FROM #Chicken;

Selecting data allows for analysis or further processing as needed.

Dropping the Temp Table

When the temp table is no longer required, drop it by running the following:

-- Drop local temp table (also happens on session disconnect) 
DROP TABLE #Chicken;

Free up resources by removing the temporary table when it’s no longer in use.

Remember: While local temp tables self-destruct at the end of a session, global temp tables demand manual cleanup. Drop global temp tables to prevent clutter and ensure efficient resource utilization.

Leave a Reply

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