SQL - Temporary Tables
In SQL, a temporary table is a table that is created and exists only for the duration of a database session. It is a useful tool for storing and manipulating temporary data within a session or query. Temporary tables can be created in different ways depending on the database system being used.
Creating a Temporary Table:
In most database systems, temporary tables are created using the CREATE TABLE statement, with the addition of the # or ## prefix before the table name. The # prefix creates a local temporary table that is only accessible within the current session, while the ## prefix creates a global temporary table that is accessible across multiple sessions.
Here is an example of creating a local temporary table named #TempTable with two columns (ID and Name):
CREATE TABLE #TempTable (
ID INT,
Name VARCHAR(50)
);
Populating Data into the Temporary Table:
Once the temporary table is created, you can insert data into it using the INSERT INTO statement, similar to inserting data into a regular table.
Here is an example of inserting data into the #TempTable:
INSERT INTO #TempTable (ID, Name)
VALUES (1, 'John'),
(2, 'Jane'),
(3, 'Mike');
Querying and Manipulating the Temporary Table:
You can perform various operations on the temporary table, including selecting, updating, deleting, and joining data, just like you would with a regular table.
Here is an example of selecting data from the #TempTable:
SELECT * FROM #TempTable;
Dropping the Temporary Table:
Once you're done using the temporary table, it's good practice to drop it to free up the system resources.
In most cases, you can drop the temporary table using the DROP TABLE statement.
Here is an example of dropping the #TempTable:
DROP TABLE #TempTable;
Note that the specific syntax and behavior of temporary tables may vary slightly depending on the database system you are using. It's always recommended to consult the documentation of your specific database system for more details and any additional features or considerations related to temporary tables.