softwaretips4u Tips that Transform
← Back to Homepage ← Back to Articles

SQL Temporary Tables vs Table Variables vs CTEs

πŸ”Ή Why This Topic Is Important

In complex SQL workflows, we often need to store intermediate query results temporarily β€” for reuse, performance optimization, or readability. SQL offers multiple ways to handle this: temporary tables, table variables, and common table expressions (CTEs). Each serves a specific use case β€” knowing when to use which one is crucial for performance and scalability.

βš™οΈ 1️⃣ Temporary Tables

A temporary table is a physical table created in tempdb that exists only for the session (or scope) in which it’s created.

CREATE TABLE #EmployeeTemp (
    EmpID INT,
    EmpName VARCHAR(100),
    Department VARCHAR(50)
);
INSERT INTO #EmployeeTemp VALUES (101, 'Suresh', 'QA'), (102, 'Sharmili', 'Dev');
SELECT * FROM #EmployeeTemp;
PropertyDescription
Prefix# (local) or ## (global)
ScopeLocal to session or connection
Stored Intempdb
Supports IndexesYes
PerformanceFaster for large datasets
UsageReused across multiple queries or stored procedures
-- Local Temporary Table
CREATE TABLE #Temp1 (id INT);

-- Global Temporary Table (accessible by other sessions)
CREATE TABLE ##TempGlobal (id INT);

βš™οΈ 2️⃣ Table Variables

A table variable is an in-memory table-like structure declared using DECLARE. They are lightweight and ideal for small datasets or procedural logic.

DECLARE @Employee TABLE (
    EmpID INT,
    EmpName VARCHAR(100)
);
INSERT INTO @Employee VALUES (201, 'Rahul'), (202, 'Neha');
SELECT * FROM @Employee;
PropertyDescription
ScopeBatch / Stored Procedure
PerformanceGood for small data; slower for large data
Transaction LoggingMinimal
IndexesOnly primary key or unique constraints
Stored InMemory (tempdb if needed)
RecompilationDoes not trigger re-optimization like temp tables

βš™οΈ 3️⃣ Common Table Expressions (CTEs)

A CTE is a temporary named query result that exists only within the execution scope of a single SQL statement. CTEs improve readability and recursion, but are not stored physically.

WITH DepartmentCount AS (
    SELECT Department, COUNT(*) AS EmpCount
    FROM Employees
    GROUP BY Department
)
SELECT *
FROM DepartmentCount
WHERE EmpCount > 5;

πŸ” Recursive CTE Example

WITH EmployeeHierarchy AS (
    SELECT EmpID, ManagerID, EmpName
    FROM Employees
    WHERE ManagerID IS NULL
    UNION ALL
    SELECT e.EmpID, e.ManagerID, e.EmpName
    FROM Employees e
    INNER JOIN EmployeeHierarchy eh ON e.ManagerID = eh.EmpID
)
SELECT *
FROM EmployeeHierarchy;
Recursive CTEs are ideal for organizational trees, category hierarchies, and traversing parent-child relationships.

βš™οΈ 4️⃣ Comparison Table

FeatureTemporary TableTable VariableCTE
ScopeSessionBatch / ProcedureSingle Query
Stored IntempdbMemory / tempdbMemory (query only)
PerformanceBest for large datasetsBest for small datasetsGreat for readable transformations
IndexesYesLimitedNo
ReusabilityYes (within session)Yes (within scope)No
TransactionsFully supportedPartially supportedN/A
Recursive Query SupportNoNoβœ… Yes
Primary Use CaseETL, intermediate result cachingProcedural logicReadability, recursion

βš™οΈ 5️⃣ Choosing the Right One

ScenarioBest Option
Store and reuse data across multiple queriesTemporary Table
Small, fast in-memory datasetTable Variable
Simplify long complex query or recursionCTE
Need indexing and statisticsTemporary Table
Inside stored procedureTable Variable

βš™οΈ 6️⃣ Real-World Example

Scenario: Fetch top-performing employees per department and reuse in multiple queries.

-- Step 1: Store result in a temporary table
SELECT * INTO #TopPerformers
FROM Employees
WHERE Rating > 4.5;

-- Step 2: Use the same temp table in next queries
SELECT Department, COUNT(*)
FROM #TopPerformers
GROUP BY Department;

-- Step 3: Clean up
DROP TABLE #TopPerformers;
Temporary tables excel when intermediate results must be reused across several statements in the same session.

πŸ’‘ Interview Tip

β€œTemporary tables, table variables, and CTEs all store intermediate data differently. For large reusable data, use temporary tables; for small scoped logic, table variables; and for readable one-time transformations, CTEs.”
← Back to Articles | 🏠 Back to Homepage