Temporary tables are one of the most powerful tools in a database developer’s arsenal, offering a flexible workspace for intermediate data processing without cluttering the permanent schema. Whether you are breaking down a complex query into manageable steps, staging data for an ETL pipeline, or simply need a scratchpad for ad-hoc analysis, understanding how to create and manage these objects is essential for writing efficient, maintainable SQL code. Unlike permanent tables, temporary tables exist only for the duration of a session or transaction, automatically cleaning themselves up when the connection closes, which makes them ideal for volatile, intermediate workloads That's the part that actually makes a difference..
Understanding the Types of Temporary Tables
Before diving into syntax, it is critical to distinguish between the two primary categories of temporary tables, as their scope and visibility differ significantly. The implementation details vary slightly across database engines like SQL Server, PostgreSQL, MySQL, and Oracle, but the core concepts remain consistent.
Local Temporary Tables
Local temporary tables are the most common variety. They are visible only to the current session or connection that created them. If you open a second query window and try to query the same table name, it will not exist—or you might even create a completely different table with the same name in that second session without conflict. In SQL Server, these are prefixed with a single hash symbol (#TableName). In PostgreSQL and MySQL, they are created using the CREATE TEMPORARY TABLE syntax. Once the session ends, the table is automatically dropped And it works..
Global Temporary Tables
Global temporary tables are visible to all sessions and users connected to the database instance. In SQL Server, these are prefixed with a double hash symbol (##TableName). They persist until the creating session ends and all other active references to the table are closed. In Oracle, the concept differs slightly: the table definition is permanent (visible to all), but the data is private to the session or transaction (ON COMMIT PRESERVE ROWS vs ON COMMIT DELETE ROWS). PostgreSQL does not have a direct equivalent to SQL Server’s global temp tables, though unlogged tables serve a similar performance purpose for session-agnostic data Small thing, real impact..
Syntax and Creation Methods by Platform
Because SQL dialects handle temporary objects differently, you must use the syntax appropriate for your specific Relational Database Management System (RDBMS). Below are the standard patterns for the most popular platforms That's the part that actually makes a difference..
SQL Server (T-SQL)
SQL Server offers two distinct ways to create temp tables: explicit definition and the SELECT INTO shortcut.
Method 1: Explicit Definition (CREATE TABLE)
This method gives you full control over data types, constraints, and indexes Worth knowing..
CREATE TABLE #EmployeeStaging (
EmployeeID INT PRIMARY KEY,
FirstName NVARCHAR(50) NOT NULL,
LastName NVARCHAR(50) NOT NULL,
HireDate DATE,
DepartmentID INT,
Salary DECIMAL(10, 2) CHECK (Salary > 0)
);
-- Insert data subsequently
INSERT INTO #EmployeeStaging (EmployeeID, FirstName, LastName, HireDate, DepartmentID, Salary)
SELECT EmployeeID, FirstName, LastName, HireDate, DepartmentID, Salary
FROM HumanResources.Employee
WHERE HireDate > '2020-01-01';
Method 2: SELECT INTO (The Developer Favorite)
This creates the table structure and populates it in a single atomic operation. The column names and data types are inferred directly from the SELECT statement. This is significantly faster to write and often faster to execute because it minimizes logging in certain recovery models The details matter here..
SELECT EmployeeID, FirstName, LastName, HireDate, DepartmentID, Salary
INTO #EmployeeStaging
FROM HumanResources.Employee
WHERE HireDate > '2020-01-01';
Note: You cannot easily add constraints (like Primary Keys) or indexes using SELECT INTO alone. You must run ALTER TABLE or CREATE INDEX statements afterward.
PostgreSQL
PostgreSQL uses the standard SQL CREATE TEMPORARY TABLE (or CREATE TEMP TABLE) syntax. It does not use a naming prefix like #; instead, the system manages visibility via a special temporary schema (pg_temp).
CREATE TEMPORARY TABLE employee_staging AS
SELECT employee_id, first_name, last_name, hire_date, department_id, salary
FROM human_resources.employee
WHERE hire_date > '2020-01-01';
-- Explicit definition with constraints
CREATE TEMP TABLE temp_departments (
dept_id SERIAL PRIMARY KEY,
dept_name VARCHAR(100) UNIQUE NOT NULL
) ON COMMIT DROP; -- Default behavior: drop at end of transaction
Crucial PostgreSQL Option: ON COMMIT
ON COMMIT PRESERVE ROWS(Default): Data persists for the session.ON COMMIT DELETE ROWS: Truncates the table after every transaction commit.ON COMMIT DROP: Drops the table entirely at the end of the transaction.
MySQL
MySQL syntax mirrors PostgreSQL closely. The keyword TEMPORARY is required. The table is visible only to the current connection.
CREATE TEMPORARY TABLE employee_staging
SELECT employee_id, first_name, last_name, hire_date, department_id, salary
FROM human_resources.employee
WHERE hire_date > '2020-01-01';
-- Explicit structure
CREATE TEMPORARY TABLE temp_sales_summary (
region_id INT,
total_sales DECIMAL(15,2),
sale_count INT,
PRIMARY KEY (region_id)
) ENGINE=MEMORY; -- Optional: Use MEMORY engine for speed if data fits in RAM
MySQL allows specifying the storage engine (e.g., ENGINE=MEMORY or ENGINE=InnoDB). Using the MEMORY engine for small, frequently accessed temp tables can yield massive performance gains, though data is lost on server restart (which aligns with the temp table lifecycle anyway) The details matter here..
Oracle
Oracle uses Global Temporary Tables (GTTs). The definition is permanent (stored in the data dictionary), but the data is private. You create the structure once (usually by a DBA during deployment), and then every session inserts into it independently Easy to understand, harder to ignore..
-- Run once during schema setup
CREATE GLOBAL TEMPORARY TABLE employee_staging (
employee_id NUMBER PRIMARY KEY,
first_name VARCHAR2(50),
last_name VARCHAR2(50),
hire_date DATE,
department_id NUMBER,
salary NUMBER(10,2)
) ON COMMIT PRESERVE ROWS; -- Or ON COMMIT DELETE ROWS
-- Application code (run per session)
INSERT INTO employee_staging
SELECT employee_id, first_name, last_name, hire_date, department_id, salary
FROM hr.employees
WHERE hire_date > DATE '2020-01-01';
Performance Optimization: Indexing and Statistics
A common misconception is that temporary tables do not need indexes because they are "small" or "temporary." In reality, adding the right indexes to a temp table can transform a 30-second query into a sub-second one, especially when joining the temp table to large permanent tables That alone is useful..
When to Index
- Join Columns: If you join
#TempTableto a permanent table onCustomerID, indexCustomerIDon the temp table. - Filter Columns: If you frequently run
WHERE Status = 'Active'against the temp table, indexStatus. - Order By / Group By: Indexing columns used in
ORDER BYorGROUP BYclauses avoids expensive sort operations.