How To Create Temp Table In Sql

5 min read

Temporary tables are a fundamental feature in SQL that allow developers and database administrators to store intermediate results for the duration of a session or transaction. Unlike permanent tables, these structures exist only temporarily, making them ideal for complex data manipulation, staging data during ETL processes, or breaking down massive queries into manageable steps. Understanding how to create temp table in sql environments is a critical skill for writing efficient, maintainable, and performant database code And it works..

Understanding Temporary Tables: Scope and Lifetime

Before diving into syntax, Grasp the two primary categories of temporary tables, distinguished by their scope and visibility — this one isn't optional. The implementation details vary slightly across database engines like SQL Server, PostgreSQL, MySQL, and Oracle, but the core concepts remain consistent.

This changes depending on context. Keep that in mind.

Local Temporary Tables

Local temporary tables are visible only to the session that created them. They are automatically dropped when the session ends or when the stored procedure that created them finishes execution. 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 and are session-scoped by default Less friction, more output..

Global Temporary Tables

Global temporary tables are visible to all sessions. In SQL Server, they use a double hash prefix (##TableName) and persist until the creating session ends and all other referencing sessions stop using them. Oracle handles this differently using CREATE GLOBAL TEMPORARY TABLE, where the table definition is permanent but the data is session-specific (or transaction-specific). PostgreSQL does not have a direct equivalent to SQL Server's global temp tables, though unlogged tables (CREATE UNLOGGED TABLE) serve a similar performance purpose for non-critical data Worth knowing..

Syntax Variations Across Major Database Engines

Because the SQL standard leaves temporary table implementation details to vendors, the exact syntax differs. Below are the standard patterns for the most popular relational database management systems (RDBMS).

SQL Server (T-SQL)

SQL Server offers the most distinct syntax separation between local and global tables.

Local Temporary Table:

CREATE TABLE #TempEmployees (
    EmployeeID INT PRIMARY KEY,
    FirstName NVARCHAR(50),
    LastName NVARCHAR(50),
    DepartmentID INT,
    HireDate DATE
);

Global Temporary Table:

CREATE TABLE ##GlobalTempStats (
    StatDate DATE,
    TotalUsers INT,
    ActiveUsers INT
);

Alternative: SELECT INTO This is a widely used shortcut in SQL Server to create the table structure and populate data simultaneously based on a query result Simple, but easy to overlook. Took long enough..

SELECT EmployeeID, FirstName, LastName, DepartmentID
INTO #TempDeptEmployees
FROM Employees
WHERE DepartmentID = 5;

PostgreSQL

PostgreSQL uses the standard-compliant TEMPORARY or TEMP keyword. The table is automatically dropped at the end of the session.

CREATE TEMPORARY TABLE temp_employees AS
SELECT employee_id, first_name, last_name, department_id
FROM employees
WHERE department_id = 5;

Note: You can also define the structure explicitly using CREATE TEMPORARY TABLE temp_name (col type, ...) without the AS SELECT clause.

MySQL

MySQL syntax is nearly identical to PostgreSQL. The keyword TEMPORARY ensures the table is visible only to the current connection.

CREATE TEMPORARY TABLE temp_employees (
    employee_id INT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    department_id INT
);

-- Or populate immediately
CREATE TEMPORARY TABLE temp_high_earners
SELECT employee_id, salary
FROM salaries
WHERE salary > 100000;

Oracle

Oracle takes a unique approach. The table definition is stored permanently in the data dictionary (visible to all sessions), but the data is private to the session or transaction.

CREATE GLOBAL TEMPORARY TABLE temp_employees (
    employee_id NUMBER PRIMARY KEY,
    first_name VARCHAR2(50),
    last_name VARCHAR2(50),
    department_id NUMBER
) ON COMMIT PRESERVE ROWS; -- Options: DELETE ROWS (transaction) or PRESERVE ROWS (session)

Practical Methods for Creation and Population

There are three primary workflows for utilizing temporary tables effectively. Choosing the right one depends on whether you know the schema beforehand or want to derive it from existing data And it works..

1. Explicit Definition (CREATE TABLE then INSERT)

Use this when you need precise control over data types, constraints (Primary Keys, Unique, Check), and indexes. This is best for staging tables where data quality enforcement is required before moving data to production tables.

-- SQL Server Example
CREATE TABLE #StagingOrders (
    OrderID INT NOT NULL,
    CustomerID INT NOT NULL,
    OrderDate DATE,
    TotalAmount DECIMAL(10, 2) CHECK (TotalAmount >= 0),
    PRIMARY KEY (OrderID)
);

INSERT INTO #StagingOrders (OrderID, CustomerID, OrderDate, TotalAmount)
SELECT OrderID, CustomerID, OrderDate, TotalAmount
FROM Orders
WHERE OrderDate >= '2023-01-01';

2. Implicit Creation (SELECT INTO / CREATE TABLE AS SELECT)

This is the fastest way to create a temp table for ad-hoc analysis. The engine infers data types and nullability from the source query. Crucially, constraints and indexes are not copied over.

  • SQL Server: SELECT ... INTO #TempTable FROM ...
  • PostgreSQL/MySQL: CREATE TEMP TABLE TempTable AS SELECT ... FROM ...
  • Oracle: CREATE GLOBAL TEMPORARY TABLE TempTable AS SELECT ... FROM ... (Requires ON COMMIT clause).

3. Using Table Variables (SQL Server Specific Alternative)

While not a "temp table," Table Variables (DECLARE @TableVar TABLE (...)) are often confused with them. They have scope limited to the batch, generate fewer recompilations, but lack statistics, making them poor choices for large datasets or complex joins. Use temp tables for datasets exceeding a few hundred rows or when indexes are needed.

Indexing and Performance Optimization

One of the biggest advantages of temporary tables over table variables or Common Table Expressions (CTEs) is the ability to create indexes and statistics. The query optimizer uses these to generate efficient execution plans The details matter here..

Creating Indexes on Temp Tables

You can add clustered and non-clustered indexes just like on permanent tables Small thing, real impact..

-- SQL Server Syntax
CREATE TABLE #SalesData (
    SaleID INT,
    ProductID INT,
    SaleDate DATE,
    Amount DECIMAL(10,2)
);

-- Create a Clustered Index (sorts physical data)
CREATE CLUSTERED INDEX IX_SalesData_Date ON #SalesData (SaleDate);

-- Create a Non-Clustered Index for lookups
CREATE NONCLUSTERED INDEX IX_SalesData_Product ON #SalesData (ProductID) INCLUDE (Amount);

Performance Tip: Create indexes after populating the table with bulk data. Inserting data into a heap (table without clustered index) and then creating the clustered index is often faster than inserting into an already indexed table, as it avoids page splits and fragmentation during the load.

Statistics and Recompilation

SQL Server automatically creates statistics on temp table columns used in predicates (WHERE clauses, JOINs). This allows the optimizer to estimate row counts accurately. Still, be aware that heavy usage of temp tables in stored procedures can lead to plan recompilation when the temp table schema changes or row counts cross thresholds. Using OPTION (RECOMPILE) or KEEPFIXED PLAN hints can manage this behavior

Just Went Up

New Content Alert

These Connect Well

A Few Steps Further

Thank you for reading about How To Create Temp Table In Sql. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home