Temp Table in SQL
A Temporary Table (often called temp table) in SQL is a special type of table that exists temporarily during a session or transaction. It is used to store intermediate results or data that you only need temporarily while running queries.
Key Points about Temporary Tables:
Scope: Temporary tables are visible only to the session (connection) that created them.
Lifetime: They are automatically dropped when the session ends or when explicitly dropped.
Used for complex query processing, storing intermediate results, or simplifying complex joins.
Syntax and behavior can vary across SQL databases.
How to Create a Temporary Table
1. SQL Server (T-SQL)
Local temp table: Prefixed with a single
#. Visible only in the session.Global temp table: Prefixed with
##. Visible to all sessions until dropped.
-- Create a local temp tableCREATE TABLE #TempEmployees ( EmployeeID INT, Name VARCHAR(50), Salary DECIMAL(10, 2));-- Insert data into temp tableINSERT INTO #TempEmployees VALUES (1, 'John Doe', 50000);-- Query temp tableSELECT * FROM #TempEmployees;-- Temp table is dropped automatically when session ends2. MySQL
MySQL uses the CREATE TEMPORARY TABLE syntax:
CREATE TEMPORARY TABLE TempEmployees ( EmployeeID INT, Name VARCHAR(50), Salary DECIMAL(10, 2));INSERT INTO TempEmployees VALUES (1, 'John Doe', 50000);SELECT * FROM TempEmployees;Temporary tables in MySQL are dropped automatically when the session ends.
3. PostgreSQL
PostgreSQL supports temporary tables similarly:
CREATE TEMPORARY TABLE TempEmployees ( EmployeeID INT, Name VARCHAR(50), Salary NUMERIC(10, 2));INSERT INTO TempEmployees VALUES (1, 'John Doe', 50000);SELECT * FROM TempEmployees;Why Use Temporary Tables?
Break down complex queries.
Store intermediate or aggregated results.
Improve performance by avoiding repeated calculations.
Simplify multi-step data transformations.
If you want, I can help you write temp table queries for your database system!