SQL | Declare Local Temporary Table
Last Updated :
16 Dec, 2024
Local temporary tables in SQL are powerful for managing intermediate data during a session or procedure. These tables enable developers to temporarily store results, perform computations, and simplify complex queries. Understanding how to declare, use, and manage local temporary tables effectively can significantly enhance database performance and organization.
In this article, we will explain declaring local temporary tables in SQL, exploring their syntax, examples, and best practices. Along the way, we’ll explain key concepts with detailed examples and outputs, ensuring a complete understanding of this essential SQL feature.
Declaring Local Temporary Tables in SQL
Local temporary tables are a type of table in SQL that exists only during the session or scope in which they are created. These tables are stored in the tempdb
database and are automatically dropped when the session or procedure ends. They are useful for temporarily storing intermediate results or data for specific tasks. They are automatically dropped when the session or procedure that created them ends.
Key Features of Local Temporary Tables:
- They are session-specific, meaning they are accessible only within the session or scope that created them.
- They are automatically deleted once the session ends, reducing manual cleanup.
- Local temporary tables are denoted by a
#
symbol at the beginning of their name.
Syntax
CREATE TABLE #TempTableName
(
Column1 DataType,
Column2 DataType,
...
);
Key Terms
#
TempTableName
: The name of the temporary table, which must start with a #
symbol to denote that it is a local temporary table.
Column1
, Column2
, ...: The columns of the table along with their data types.
Example 1: Declaring and Using a Local Temporary Table
Let’s create a local temporary table named #TempGeek
, insert values into it, and retrieve the data. This example demonstrates how temporary tables can be utilized to store intermediate results. By using temporary tables, we can optimize queries for better performance and clarity.
Query:
DECLARE LOCAL TEMPORARY TABLE TempGeek ( number INT );
INSERT INTO Geeks
VALUES (1), (2), (3), (4);
Select *
from TempGeek;
Output
Explanation:
- The
CREATE TABLE
statement defines the structure of the local temporary table #TempGeek
with a single column named number
of type INT
.
- Once we create a local temporary table, we cannot create another temporary table of that name for as long as the temporary table exists.
Example 2: Attempting to Create a Temporary Table with the Same Name
If we try to create a temporary table with the same name in the same session, SQL will throw an error. This ensures that each temporary table name within a session is unique, preventing conflicts and unintended data overwrites
Query:
declare local temporary table Geektable
Explanation:
- Once a local temporary table is created, attempting to create another table with the same name in the same session results in an error.
- This ensures unique naming and prevents conflicts within a session.
Example 3: Local Temporary Table Shadowing Base Tables
We can create a local temporary table with the same name as an existing base table. The local temporary table takes precedence within the session, effectively shadowing the base table until the temporary table is dropped or the session ends.
Query:
CREATE TABLE Geeks (num INT);
INSERT INTO Geeks VALUES (9), (8);
CREATE TABLE #Geeks (num INT);
INSERT INTO #Geeks VALUES (6), (7);
SELECT *
FROM #Geeks;
Output
Explanation:
- The base table
Geeks
is created and populated with values (9, 8)
.
- A local temporary table
#Geeks
with the same name is then created and populated with values (6, 7)
.
- Any reference to
Geeks
within the session will prioritize the local temporary table #Geeks
.
Example 4: Dropping a Local Temporary Table
Local temporary tables are automatically dropped when the session ends. However, if we no longer need the temporary table during the session, we can manually drop it using the DROP TABLE
statement.
Query:
DROP TABLE #TempGeek;
Explanation:
- The
DROP TABLE
statement deletes the temporary table #TempGeek
from the session.
- This is useful for manually managing temporary tables when they are no longer needed.
Common Errors with Local Temporary Tables
- Creating Temporary Tables with Duplicate Names in the Same Session:
- Attempting to create a temporary table with the same name in the same session throws an error.
- Ensure unique names or drop the existing table before creating a new one.
- Referencing Dropped Temporary Tables:
- Once a temporary table is dropped, it cannot be referenced.
- Always verify the existence of a temporary table before using it in queries.
Conclusion
Local temporary tables are an indispensable feature of SQL for managing temporary data within the scope of a session or procedure. They provide a flexible, efficient, and organized way to handle intermediate results, perform complex computations, and simplify query logic. By understanding how to declare, use, and manage local temporary tables effectively, we can enhance the performance and clarity of our SQL operations.
Similar Reads
SQL Server TEMPORARY TABLE
A temporary SQL table also known as a temp table is created in the database only for a specific session to store the data temporarily which is needed for a short duration of time. In this article, we are going to learn about SQL Server temporary tables, their types, how to use them, and why they are
5 min read
PostgreSQL - Temporary Table
A PostgreSQL temporary table is a powerful tool for managing session-specific data that only needs to exist for a short duration. Temporary tables are created within a database session or transaction and are automatically dropped when the session ends, making them ideal for intermediate data storage
4 min read
MySQL Temporary Table
Do you want to store the intermediate results of your query in some table but only for a given DB session and not persist for the lifetime? Is there some way to hold temporary data for a short time without making it permanent on the database forever? If you have ever thought about this and wondered
5 min read
What is Temporary Table in SQL?
A temporary table in SQL is an important tool for maintaining intermediate results during query execution. They help store temporary data without affecting the underlying permanent tables. In this article, weâll explore temporary tables in SQL, their types (local vs. global), and how to use them eff
3 min read
Dynamic SQL and Temporary Tables in SQL Server
In SQL Server, creating and using Temp Tables using dynamic SQL is a good feature when we need to temporarily create tables at run time and delete automatically all within a session. They can be very useful when we need to store temporary data in a structured format and do data manipulation using Da
6 min read
Select into and temporary tables in MS SQL Server
In SQL Server, the SELECT INTO TEMP TABLE statement is used to select data from one or more source tables and insert it into a temporary table. Temporary tables are extremely useful when dealing with intermediate results, or when working with subsets of data within a session without modifying or aff
4 min read
How to Drop a Temporary Table If It Exists
Temporary tables are an essential feature in database management systems like MySQL and SQL Server. They allow developers to store intermediate data for the duration of a session by providing flexibility and efficiency in handling complex queries. Managing these tables correctly including knowing ho
4 min read
How to Declare a Variable in PL/SQL?
Declaring variables in PL/SQL is a fundamental step towards building powerful and efficient database applications. Variables act as placeholders for data which enable us to manipulate and store information within our PL/SQL programs. Here, we will explore various methods of declaring variables in PL
5 min read
SQL Server TRUNCATE TABLE
The TRUNCATE TABLE command in SQL Server allows you to rapidly and effectively remove every record from a table while maintaining the table structure. The TRUNCATE TABLE command is a more lightweight operation that is usually faster for large datasets than the DELETE statement, which eliminates rows
6 min read
PL/SQL Derived Tables
Derived Tables in PL/SQL are temporary result sets that are created within the execution of a SQL statement. These are essential tools that allow developers to create temporary result sets within SQL statements. This feature enables complex queries to be simplified and enhances readability by encaps
4 min read