Temporary Tables in Azure Synapse Dedicated SQL Pool | Azure Synapse Analytics Tutorial

Temporary Tables in Azure Synapse Dedicated SQL Pool

Temporary Tables in Azure Synapse Dedicated SQL Pool

๐Ÿ“˜ What is a Temporary Table?

A temporary table in Azure Synapse Dedicated SQL Pool is a session-scoped table used to store intermediate or staging data during query processing or transformations. These tables are automatically dropped when the session ends and are stored on the compute node’s local disk, which makes them faster for temporary operations.

✅ Benefits of Temporary Tables

  • Session-local: Not visible to other users or sessions
  • Automatically dropped at the end of the session
  • Faster performance due to use of local disk
  • Supports HASH and ROUND_ROBIN distribution methods

๐Ÿ› ️ Example 1: Create a Basic Temporary Table

IF OBJECT_ID('tempdb..#CustomerStage') IS NOT NULL
    DROP TABLE #CustomerStage;

CREATE TABLE #CustomerStage
(
    CustomerID INT,
    FirstName NVARCHAR(50),
    LastName NVARCHAR(50),
    Country NVARCHAR(50)
)
WITH (
    DISTRIBUTION = HASH(CustomerID),
    HEAP
);

Insert Sample Data

INSERT INTO #CustomerStage (CustomerID, FirstName, LastName, Country)
VALUES (1, 'Alice', 'Smith', 'USA'),
       (2, 'Bob', 'Lee', 'Canada');

Query the Data

SELECT * FROM #CustomerStage;

๐Ÿ› ️ Example 2: Create Temp Table Using CTAS

You can also use CTAS (Create Table As Select) to create a temp table based on the results of a query.

IF OBJECT_ID('tempdb..#TopCustomers') IS NOT NULL
    DROP TABLE #TopCustomers;

CREATE TABLE #TopCustomers
WITH (
    DISTRIBUTION = HASH(CustomerID),
    HEAP
)
AS
SELECT TOP 1 *
FROM #CustomerStage
ORDER BY CustomerID DESC;

Query the CTAS Table

SELECT * FROM #TopCustomers;

๐Ÿงน Cleanup (Optional)

DROP TABLE #TopCustomers;
DROP TABLE #CustomerStage;

๐Ÿ“Œ Best Practices and Notes

  • Use #TempTableName syntax for session-level temporary tables.
  • Ideal for staging, transformation, or intermediate query steps.
  • Only HASH and ROUND_ROBIN distribution methods are supported.
  • Views cannot be created on temporary tables.
  • CTAS helps improve modularity and performance of temp table creation.

๐Ÿ“บ Watch the Video Tutorial

๐Ÿ“š Credit: Content created with the help of ChatGPT and Gemini.