Save Big on Cyber Monday! Up to 40% Off
ends in   {{days}}
Days
{{timeFormat.hours}}
:
{{timeFormat.minutes}}
:
{{timeFormat.seconds}}

How to create and optimize indexes on temp tables in SQL Server

SQL Server temp tables support indexes just like regular tables: you can add clustered and nonclustered indexes, primary keys, and unique constraints. A well-chosen index speeds up joins, filtering, sorting, and repeated reads of the same intermediate data. However, each index costs CPU, I/O, and tempdb space to build and maintain, so it pays off only when the temp table is large enough and queried often enough.

This guide shows when to index a temp table, how to create clustered and nonclustered indexes with T-SQL, and how to verify with execution plans and I/O statistics whether an index actually improves performance. The examples use the AdventureWorks2025 sample database and dbForge Studio for SQL Server, a SQL Server GUI tool with a built-in query profiler.

Quick reference: When should you index a temp table?

Consider indexing a temp table when queries repeatedly filter, join, or sort its data. Use the following scenarios as a starting point, then compare the complete workload with and without the index.

Scenario Indexing approach What to check
The temp table is read once in a full scan Start without an index Whether any query savings justify the cost of creating the index
Queries repeatedly retrieve a small subset of rows Consider a nonclustered index on the filter columns Logical reads, rows read, and the cost of additional lookups
Queries frequently select date or numeric ranges Consider a clustered index on the range column Whether the execution plan uses an efficient range seek
The temp table is repeatedly joined to other tables Consider an index on the join columns Join strategy, logical reads, and total execution time
A frequent query retrieves the same few columns Consider a covering nonclustered index with included columns Whether the index eliminates lookups without adding excessive build and maintenance costs
Duplicate values must be rejected during loading Define a primary key or unique index before inserting data Whether the key matches the required uniqueness rule

There is no fixed row count at which an index becomes worthwhile. The benefit depends on data distribution, query selectivity, and how often the table is accessed. Include data loading, index creation, and query execution when comparing total execution time.

What is a temp table in SQL Server?

A SQL temp table is a table that SQL Server creates in the tempdb system database to hold intermediate results for a limited time. It supports most operations of a regular table: INSERT, UPDATE, DELETE, joins, statistics, indexes, and constraints, except FOREIGN KEY constraints, which SQL Server skips with a warning.

Temp tables are typically used to break a complex query into simpler steps, to stage data for further processing, or to store a result set that a stored procedure reads several times. Because SQL Server keeps statistics on temp tables, the query optimizer can build accurate execution plans for queries that use them, and that is what makes indexing them worthwhile.

Local vs global temp tables

SQL Server has two types of temp tables, which differ in scope and visibility:

  • Local temp tables (#TempTable) are visible only in the session that created them. SQL Server drops a local temp table automatically when the session ends or, if the table was created inside a stored procedure, when the procedure completes.
  • Global temp tables (##TempTable) are visible to all sessions. SQL Server drops a global temp table when the session that created it ends and no other session is using it.

Local temp tables are far more common in stored procedures and query optimization. When you create a temp table in a SQL Server stored procedure, use a local one: it is isolated from other sessions, so parallel executions of the procedure never conflict.

Both local and global temp tables support ALTER TABLE after creation, just like regular tables. For example, to add a new column to an existing temp table:

ALTER TABLE #Orders
ADD Discount DECIMAL(5,2);
Comparison Local temporary table Global temporary table
Creation CREATE TABLE #<table_name>
or SELECT … INTO #<table_name>
CREATE TABLE ##<table_name>
or SELECT … INTO ##<table_name>
Availability Only in the session that created it In all user sessions on the same SQL Server instance
Deletion When the creating session closes, or with DROP TABLE #<table_name>; When the creating session closes and no other session uses it, or with DROP TABLE ##<table_name>;
Change of definition Supported Supported
Constraints Supported, except FOREIGN KEY Supported, except FOREIGN KEY
Indexes Supported Supported
Name Must be unique within the session that created it Must be unique across all sessions and the entire tempdb database
Storage The tempdb system database The tempdb system database
Transactions Supported (changes are rolled back) Supported (changes are rolled back)
Statistics Supported Supported

How to create a temp table in SQL Server: syntax and examples

There are two ways to create a temp table in SQL Server: define it explicitly with CREATE TABLE and then fill it with INSERT INTO, or create and fill it in one statement with SELECT INTO. The choice affects how much control you have over column definitions and when you can add indexes.

CREATE TABLE and INSERT INTO

The explicit approach defines the table structure first and loads the data in a separate statement. The example creates a local temp table and then uses a SQL INSERT INTO statement to load the temp table with orders from the AdventureWorks2025 database:

USE AdventureWorks2025;
GO

CREATE TABLE #Orders
(
    SalesOrderID INT NOT NULL,
    CustomerID INT NOT NULL,
    OrderDate DATETIME NOT NULL,
    TotalDue MONEY NOT NULL
);

INSERT INTO #Orders (SalesOrderID, CustomerID, OrderDate, TotalDue)
SELECT SalesOrderID, CustomerID, OrderDate, TotalDue
FROM Sales.SalesOrderHeader;
Creating and populating a temp table in dbForge Studio for SQL Server

This method gives you direct control over column data types, nullability, constraints, and index definitions. It is a good choice for stored procedures and for temp tables whose structure must stay predictable and independent of the source query.

When you need to load a large volume of data into a temp table from a file rather than from another table, use BULK INSERT instead of row-by-row INSERT statements:

BULK INSERT #Orders
FROM 'C:\Import\Orders.csv'
WITH
(
    FIELDTERMINATOR = ',',
    ROWTERMINATOR = '\n',
    FIRSTROW = 2
);

BULK INSERT minimizes logging and avoids the per-row overhead of individual INSERT statements, which matters for temp tables that stage large external data sets before indexing.

If the script may run several times in the same session, drop the table before creating it:

-- SQL Server 2016 and later
DROP TABLE IF EXISTS #Orders;

-- SQL Server 2014 and earlier
IF OBJECT_ID('tempdb..#Orders') IS NOT NULL
    DROP TABLE #Orders;

SELECT INTO #TempTable

In SQL Server, SELECT INTO a temp table creates it and fills it with the query result in a single statement. The example first removes the #Orders table created above with DROP TABLE IF EXISTS, the standard way to drop a temp table if it exists in SQL Server 2016 and later:

DROP TABLE IF EXISTS #Orders;

SELECT SalesOrderID,
       CustomerID,
       OrderDate,
       TotalDue
INTO #Orders
FROM Sales.SalesOrderHeader;

SQL Server derives the column names, data types, and nullability from the SELECT result, so you do not have to define the table in advance. This is convenient for quick ad hoc analysis and for staging data whose structure matches an existing table or query.

Note that SELECT INTO copies only the data and the column definitions. It does not copy indexes, primary keys, or other constraints from the source table, so the new temp table is a heap until you add indexes yourself.

CREATE TABLE vs SELECT INTO when indexes are required

If the temp table needs indexes, CREATE TABLE usually gives you more control: you can declare a primary key and inline indexes in the table definition and load the data afterward. With SELECT INTO, you always create indexes as a separate step after the data is loaded. Some external tools can also reject SELECT INTO. For example, Dataiku validates SQL query recipes without running DDL statements, and because SELECT INTO creates a table, validation fails, while the same logic split into CREATE TABLE and INSERT INTO passes.

Factor CREATE TABLE SELECT INTO
Column definitions Explicit Derived from the query
Constraints at creation Easy to define Added later
Index planning More controlled, inline indexes supported Indexes created afterward
Quick staging Good Very convenient
Readability High High for simple cases

How to create an index on a temp table in SQL Server

Yes, SQL Server allows indexes on temporary tables, including clustered and nonclustered indexes. You create them with the same CREATE INDEX statement that you use for regular tables, and SQL Server stores them in tempdb together with the table.

Index names on temp tables only need to be unique within the table, so the same procedure can run in many sessions at once without naming conflicts. The examples below use the #Orders table created in the previous section.

Create a nonclustered index on a temp table

A nonclustered index is a separate structure that stores the key column values with pointers to the table rows. Create one on the column you filter or join by most often:

CREATE NONCLUSTERED INDEX IX_Orders_CustomerID
ON #Orders (CustomerID);

Now consider a query that returns the orders of one customer:

SELECT SalesOrderID, OrderDate, TotalDue
FROM #Orders
WHERE CustomerID = 29825;

Without the index, SQL Server performs a Table Scan: it reads every row of #Orders and checks the condition for each one. With the index, the optimizer can choose an Index Seek to go directly to the rows of customer 29825 and then look up the remaining columns in the table. Whether it does so depends on how selective the condition is: for a value that matches a large share of rows, a scan can still be cheaper.

Index Seek on a temp table in the execution plan in dbForge Studio for SQL Server

If the query always returns the same few columns, add them to the index with INCLUDE. Such a covering index contains every column the query needs and answers it without extra lookups. The DROP_EXISTING option replaces the index created above instead of failing with a duplicate name error:

CREATE NONCLUSTERED INDEX IX_Orders_CustomerID
ON #Orders (CustomerID)
INCLUDE (SalesOrderID, OrderDate, TotalDue)
WITH (DROP_EXISTING = ON);

Create a clustered index on a temp table

A clustered index defines the logical order of the table rows, so a table can have only one. It works best for range queries and ordered access. The example below starts from a freshly loaded #Orders heap, so no nonclustered indexes have to be rebuilt:

DROP TABLE IF EXISTS #Orders;

SELECT SalesOrderID, CustomerID, OrderDate, TotalDue
INTO #Orders
FROM Sales.SalesOrderHeader;

CREATE CLUSTERED INDEX IX_Orders_OrderDate
ON #Orders (OrderDate);

After that, the optimizer can use a range seek for a date range query and read only the part of the index that holds the matching rows:

SELECT SalesOrderID, CustomerID, TotalDue
FROM #Orders
WHERE OrderDate >= '20240101'
  AND OrderDate < '20240401';

Building a clustered index on a populated table rewrites the whole table in key order, which is costly for large temp tables. If you need a clustered index, create it first and add nonclustered indexes after it; otherwise, SQL Server rebuilds the existing nonclustered indexes when the clustered one is created.

Note that a clustered index does not guarantee the order of query results. If you need sorted output, add ORDER BY to the query.

Create a primary key on a temp table

You can declare a primary key directly in the table definition. The examples in this section recreate #Orders as alternative definitions of the same table:

DROP TABLE IF EXISTS #Orders;

CREATE TABLE #Orders
(
    SalesOrderID INT PRIMARY KEY,
    CustomerID INT NOT NULL,
    OrderDate DATETIME NOT NULL,
    TotalDue MONEY NOT NULL
);

SQL Server enforces a primary key with a unique index, which is clustered by default. Add a primary key when the temp table has a natural unique column and you join or look up rows by it. Not every temp table needs one: for a table that is read once in a full scan, a primary key does not improve query performance, although it still prevents duplicate keys.

Avoid giving primary key and other constraints on temp tables explicit names. Constraint names must be unique in tempdb, so if a stored procedure creates a temp table with a named constraint, concurrent executions of the procedure can fail with a duplicate name error. Unnamed constraints get unique system-generated names.

Starting with SQL Server 2014, you can also declare nonclustered indexes inline in CREATE TABLE. In stored procedures, this has an extra benefit: SQL Server can cache and reuse the temp table between executions, while a separate CREATE INDEX statement after the table is created prevents such caching.

DROP TABLE IF EXISTS #Orders;

CREATE TABLE #Orders
(
    SalesOrderID INT NOT NULL PRIMARY KEY CLUSTERED,
    CustomerID INT NOT NULL,
    OrderDate DATETIME NOT NULL,
    TotalDue MONEY NOT NULL,
    INDEX IX_Orders_CustomerID NONCLUSTERED (CustomerID)
);

Create indexes before or after inserting data

For most temp tables loaded in one batch, create nonclustered indexes after inserting the data. Building an index once on a populated table is cheaper than updating it for every inserted row, and SQL Server creates index statistics from all of the data.

Define the index before loading when you need it to enforce uniqueness during the load, when the table is filled in many small steps and queried in between, or when you use inline indexes to keep temp table caching in stored procedures.

Clustered vs nonclustered indexes on temp tables

Use a clustered index for the column that defines how the temp table is most often read: a range filter, an ORDER BY, or a join key that is used repeatedly. Use nonclustered indexes for selective lookups on other columns.

Factor Clustered index Nonclustered index
Row organization Determines the logical order of rows Separate index structure
Number per table One Multiple
Good for Range scans, ordered access, repeated joins Selective filtering and lookups
Creation cost Can be significant, the whole table is rewritten Depends on table size and key width
Best candidate Frequently used ordering or join key Common WHERE and JOIN columns

For small temp tables with a few hundred rows, indexes rarely matter: a scan of a few pages is already fast, and creating the index can take longer than the query itself.

Why is SQL Server not using my temp table index?

Creating an index does not guarantee that SQL Server will use it. The optimizer compares available access methods and may choose a scan when it estimates that scanning will cost less than using the index.

Possible reason What to inspect in the actual execution plan What to consider
The temp table is small A Table Scan or Clustered Index Scan with few logical reads and a short execution time Keep the scan if the complete workload is already efficient. Creating an index may cost more than it saves.
The filter returns a large proportion of rows Compare the number of rows returned with the total number of rows in the temp table A scan may be appropriate. Check whether the index matches the query’s filter columns and whether the filter is selective enough to benefit from a seek.
Retrieving additional columns requires too many lookups Look for Key Lookup or RID Lookup operators, their execution counts, and associated logical reads in a plan that uses the index Consider including frequently retrieved columns in the nonclustered index. Measure whether fewer lookups justify the larger index.
The filter applies a function or conversion to the indexed column Inspect predicates for expressions such as YEAR(OrderDate) or implicit conversions involving the indexed column Where possible, rewrite the condition to compare the column directly with a value or range, and use matching data types.
Estimated row counts differ substantially from actual row counts Compare Estimated Number of Rows with Actual Number of Rows, especially at the temp table access and join operators Investigate statistics, data changes, and cached plan reuse. Test a targeted statistics update or statement recompilation when appropriate.

An Index Seek is not automatically faster than a scan. Compare logical reads, CPU time, elapsed time, and the cost of building and maintaining the index before changing the query or index definition.

How to check whether a temp table index improves performance

To find out whether an index helps, run the same query with and without it and compare I/O statistics, execution time, and the actual execution plan. The examples in the previous sections are independent, so start from a freshly loaded heap: the script below recreates #Orders without indexes, enables the statistics output, and runs the query. Then create the index and run the query again:

-- Recreate and load #Orders without indexes
DROP TABLE IF EXISTS #Orders;

SELECT SalesOrderID, CustomerID, OrderDate, TotalDue
INTO #Orders
FROM Sales.SalesOrderHeader;

SET STATISTICS IO ON;
SET STATISTICS TIME ON;

SELECT SalesOrderID, OrderDate, TotalDue
FROM #Orders
WHERE CustomerID = 29825;

SET STATISTICS IO OFF;
SET STATISTICS TIME OFF;

Then compare the following metrics:

  • Logical reads show how many data pages the query read from memory. This is the most stable indicator of index efficiency.
  • CPU time and elapsed time show the actual cost of the query. Run the query several times, because the first run may include compilation and disk reads.
  • Access method shows how SQL Server reads the temp table: Table Scan or Clustered Index Scan reads all rows, Index Seek reads a range of the index. A seek can still read rows that are filtered out later, so also compare the number of rows read with the number of rows returned and check for lookups.
  • Estimated vs actual row counts reveal outdated or missing statistics. A large difference means the optimizer chose the plan based on a wrong estimate.

Remember to include the cost of creating the index. If the index saves less time than it takes to build, the temp table is better left without it. The full workload test below shows how to measure this.

In dbForge Studio for SQL Server, you can collect all these metrics in one place with Query Profiler. It displays the execution plan diagram, CPU time, logical reads, and table I/O for each run, and saves the profiling results so that you can compare the query before and after indexing.

Comparing query profiling results with and without a temp table index in dbForge Studio for SQL Server

Does the index pay off? Testing the full workload

A faster query does not mean that the index pays off: building it also takes time. To see the full picture, measure the complete work with the temp table: loading the data, creating the index, and running all queries against it.

The test below compares three configurations of the same #Orders table without a clustered index:

  • Heap: no index
  • Nonclustered index: ON #Orders (CustomerID)
  • Covering index: ON #Orders (CustomerID) INCLUDE (SalesOrderID, OrderDate, TotalDue)

Each configuration runs the query for customer 29825 once, 10 times, and 100 times. These are test scenarios, not universal thresholds.

Test conditions:

  • SQL Server 2025 Express Edition (17.0.1000.7)
  • AdventureWorks2025 sample database, compatibility level 170
  • 31,465 rows in #Orders, 12 rows for customer 29825
  • 30 measured runs of each scenario after one warm-up run; the table is dropped and recreated before every run, and the results show the average
  • Query results are assigned to variables, so returning rows to the client does not affect the timings
Show the full test script
SET NOCOUNT ON;

DECLARE @CustomerID INT = 29825, @MeasuredRuns INT = 30;

SELECT SERVERPROPERTY('ProductVersion') AS SqlServerVersion,
       SERVERPROPERTY('Edition') AS Edition,
       DB_NAME() AS DatabaseName,
       (SELECT compatibility_level FROM sys.databases WHERE name = DB_NAME()) AS CompatibilityLevel,
       (SELECT COUNT(*) FROM Sales.SalesOrderHeader) AS TotalRows,
       (SELECT COUNT(*) FROM Sales.SalesOrderHeader WHERE CustomerID = @CustomerID) AS CustomerRows;

DROP TABLE IF EXISTS #Results;
CREATE TABLE #Results
(
    Config VARCHAR(20) NOT NULL,
    Executions INT NOT NULL,
    RunNo INT NOT NULL,
    LoadUs BIGINT NOT NULL,
    BuildUs BIGINT NULL,
    QueryUs BIGINT NOT NULL,
    QueryReads BIGINT NOT NULL
);

DECLARE @Configs TABLE (Id INT, Config VARCHAR(20));
INSERT INTO @Configs VALUES (1, 'Heap'), (2, 'Nonclustered index'), (3, 'Covering index');
DECLARE @Counts TABLE (Executions INT);
INSERT INTO @Counts VALUES (1), (10), (100);

DECLARE @Id INT, @Config VARCHAR(20), @Executions INT, @Run INT, @i INT,
        @t0 DATETIME2(7), @t1 DATETIME2(7), @t2 DATETIME2(7), @t3 DATETIME2(7),
        @r0 BIGINT, @r1 BIGINT,
        @SalesOrderID INT, @OrderDate DATETIME, @TotalDue MONEY;

DECLARE cases CURSOR LOCAL FAST_FORWARD FOR
    SELECT c.Id, c.Config, n.Executions FROM @Configs AS c CROSS JOIN @Counts AS n ORDER BY n.Executions, c.Id;
OPEN cases;
FETCH NEXT FROM cases INTO @Id, @Config, @Executions;
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @Run = 0;
    WHILE @Run <= @MeasuredRuns -- run 0 is a warm-up and is not recorded
    BEGIN
        DROP TABLE IF EXISTS #Orders;
        CREATE TABLE #Orders
        (
            SalesOrderID INT NOT NULL,
            CustomerID INT NOT NULL,
            OrderDate DATETIME NOT NULL,
            TotalDue MONEY NOT NULL
        );

        SET @t0 = SYSDATETIME();
        INSERT INTO #Orders (SalesOrderID, CustomerID, OrderDate, TotalDue)
        SELECT SalesOrderID, CustomerID, OrderDate, TotalDue
        FROM Sales.SalesOrderHeader;
        SET @t1 = SYSDATETIME();

        IF @Id = 2
            CREATE NONCLUSTERED INDEX IX_Orders_CustomerID
            ON #Orders (CustomerID);
        ELSE IF @Id = 3
            CREATE NONCLUSTERED INDEX IX_Orders_CustomerID
            ON #Orders (CustomerID)
            INCLUDE (SalesOrderID, OrderDate, TotalDue);
        SET @t2 = SYSDATETIME();

        SELECT @r0 = logical_reads FROM sys.dm_exec_requests WHERE session_id = @@SPID;
        SET @i = 0;
        WHILE @i < @Executions
        BEGIN
            SELECT @SalesOrderID = SalesOrderID, @OrderDate = OrderDate, @TotalDue = TotalDue
            FROM #Orders
            WHERE CustomerID = @CustomerID;
            SET @i += 1;
        END;
        SET @t3 = SYSDATETIME();
        SELECT @r1 = logical_reads FROM sys.dm_exec_requests WHERE session_id = @@SPID;

        IF @Run > 0
            INSERT INTO #Results
            VALUES (@Config, @Executions, @Run,
                    DATEDIFF_BIG(MICROSECOND, @t0, @t1),
                    CASE WHEN @Id = 1 THEN NULL ELSE DATEDIFF_BIG(MICROSECOND, @t1, @t2) END,
                    DATEDIFF_BIG(MICROSECOND, @t2, @t3),
                    @r1 - @r0);
        SET @Run += 1;
    END;
    FETCH NEXT FROM cases INTO @Id, @Config, @Executions;
END;
CLOSE cases;
DEALLOCATE cases;
DROP TABLE IF EXISTS #Orders;

-- Averages of the measured runs, in milliseconds
SELECT Executions AS [Query executions],
       Config AS [Table configuration],
       CAST(AVG(LoadUs * 1.0) / 1000 AS DECIMAL(10, 2)) AS [Load time, ms],
       CAST(AVG(BuildUs * 1.0) / 1000 AS DECIMAL(10, 2)) AS [Index build time, ms],
       CAST(AVG(QueryUs * 1.0) / 1000 AS DECIMAL(10, 2)) AS [Query time, ms],
       CAST(AVG((LoadUs + ISNULL(BuildUs, 0) + QueryUs) * 1.0) / 1000 AS DECIMAL(10, 2)) AS [Total time, ms],
       AVG(QueryReads) AS [Logical reads (queries)]
FROM #Results
GROUP BY Config, Executions
ORDER BY Executions,
         CASE Config WHEN 'Heap' THEN 1 WHEN 'Nonclustered index' THEN 2 ELSE 3 END;

The system timer on the test server has a resolution of about 15.6 ms, so a single measurement of a short operation is rounded to 0 or 15.6 ms. Averaging 30 runs smooths out this rounding. Results, average of 30 runs:

Query executions Table configuration Load time, ms Index build time, ms Query time, ms Total time, ms Logical reads (queries)
1 Heap 13.02 — <0.5* 13.02 129
1 Nonclustered index 11.97 20.84 <0.5 32.81 14
1 Covering index 13.01 26.05 <0.5 39.06 2
10 Heap 13.54 — 18.75 32.29 1,290
10 Nonclustered index 12.50 20.31 0.52 33.34 140
10 Covering index 10.93 28.65 <0.5 39.59 20
100 Heap 12.50 — 190.11 202.61 12,900
100 Nonclustered index 13.54 20.32 3.12 36.98 1,400
100 Covering index 11.99 26.56 1.04 39.59 200

* A single table scan is shorter than the timer resolution, so this measured value is not accurate. For reference, the 10- and 100-query runs suggest that one scan takes about 1.9 ms; this estimate is not part of the measured results.

The logical reads explain the difference. Without an index, every execution scans the whole table: 129 reads per query. The nonclustered index reduces this to 14 reads: an Index Seek finds the 12 matching rows, and a lookup retrieves the remaining columns for each of them. The covering index needs only 2 reads, because the index itself contains every column the query returns.

What this test shows:

  • One query: the heap had the lowest measured average total time. Building an index takes longer than the scan it saves.
  • 10 queries: the heap and the nonclustered index produced similar average total times.
  • 100 queries: both indexes were clearly faster, about 5 times in total. The heap spends most of its time on repeated scans.
  • Covering vs nonclustered: the covering index reads 7 times fewer pages and runs 100 queries about 3 times faster, but it consistently takes longer to build. Up to 100 executions, it showed no total-time advantage over the nonclustered index.

These measurements do not establish the exact break-even point: the differences at 10 executions are smaller than the variation between runs.

Keep the limitations of this test in mind. Even after averaging, timings of a few milliseconds are approximate, and some query times are below what the timer can measure; logical reads are a more reliable comparison. The results apply to this table size, this data distribution, and this query. Larger tables, less selective filters, or a different number of queries can move the break-even point, so run a similar test on your own workload before deciding on an index.

Temp table vs table variable vs CTE

The SQL Server temp table vs table variable choice mostly depends on data size and whether you need statistics, while CTE vs temp table in SQL comes down to whether the intermediate result must be stored and reused. Choose a temp table when the intermediate result is large, used in several statements, or needs indexes and statistics. Table variables suit small data sets. A CTE defines a named result set within a single statement: it makes complex queries easier to read and supports recursion, but it does not store intermediate results.

Feature Temp table Table variable CTE
Reusable across statements Yes Yes, within the batch No, single statement only
Indexes Yes, any time Limited, inline in DECLARE only No
Column statistics Yes No Uses statistics of base tables
Stores intermediate results Yes, in tempdb Yes, in tempdb No, evaluated as part of the query
Good for repeated joins and filtering Yes Sometimes Depends

Table variables do not have column statistics, so the optimizer may underestimate how many rows they hold and choose an inefficient plan for large data sets. SQL Server 2019 improved this with deferred compilation for databases with compatibility level 150 or higher: the optimizer uses the actual row count at first execution, but still has no column statistics. Temp tables remain the safer choice for big intermediate results. A CTE is not stored anywhere: SQL Server expands it into the query each time it is referenced, so it cannot be indexed.

Best SQL IDEs and tools for temp table index optimization

You create indexes on temp tables with T-SQL, so any SQL Server IDE will do. The difference between tools is how well they help you analyze execution plans, logical reads, CPU time, and query behavior.

Tool Relevant features
dbForge Studio for SQL Server Query Profiler with execution plans, CPU time, logical reads, and table I/O; comparison of profiling results; T-SQL editor with code completion
SQL Server Management Studio (SSMS) Native execution plans, CREATE INDEX, statistics, and SQL Server administration
DataGrip SQL editing and execution plan analysis
DbVisualizer SQL editing and query execution

Temp table indexing best practices and common mistakes

Following a few temp table indexing best practices helps you avoid unnecessary overhead and misleading test results. Avoid these common mistakes when creating and evaluating temp table indexes.

Mistake Why it matters Better approach
Creating indexes on every filter or join column Each index consumes tempdb space and adds build and maintenance costs Start with indexes that support the most expensive or frequently executed queries, then measure the complete workload
Creating a covering index that omits a required column SQL Server may still need lookups to retrieve columns missing from the index Check all columns used by the query, including those in SELECT, JOIN, and filter conditions
Creating nonclustered indexes before a planned clustered index Creating the clustered index changes row locators and causes existing nonclustered indexes to be rebuilt Create the clustered index first when both index types are required
Running alternative examples without resetting the table Repeated CREATE TABLE or CREATE INDEX statements can fail because the object already exists Drop and recreate the temp table between independent tests, or explicitly replace the existing index
Measuring only the final SELECT Faster reads may not offset the time spent creating and maintaining the index Include data loading, index creation, modifications, and all subsequent queries in the comparison
Choosing an index based on one execution Compilation, caching, and concurrent activity can distort timings Repeat tests under comparable conditions and review logical reads alongside CPU and elapsed time
Assuming an index guarantees sorted results SQL Server can return rows in a different order depending on the execution plan Use ORDER BY whenever the result must follow a specific order

Choose indexes for the queries that actually use the temp table, and keep only those whose benefits justify their total cost.

Conclusion

Indexes on SQL Server temp tables work the same way as on regular tables and can noticeably speed up queries that filter, join, or sort large intermediate results. Create them deliberately: prefer CREATE TABLE when you plan indexes, load the data before adding nonclustered indexes, and avoid indexing small tables that are read only once. Most importantly, measure the result with execution plans and I/O statistics instead of assuming that an index helps.

To profile your queries and compare execution plans before and after indexing, download dbForge Studio for SQL Server and try it free for 30 days.

FAQ

Can you create an index on a temp table in SQL Server?

Yes. SQL Server supports clustered and nonclustered indexes, primary keys, and unique constraints on both local (#) and global (##) temp tables. You create them with the regular CREATE INDEX statement or declare them inline in CREATE TABLE.

Should indexes be created before or after inserting data?

In most cases, after. Building an index once on a populated temp table is cheaper than maintaining it for every inserted row. Create the index first when it must enforce uniqueness during the load or when you declare inline indexes to keep temp table caching in stored procedures.

Can a temp table have a clustered index?

Yes. A temp table can have one clustered index, created with CREATE CLUSTERED INDEX or by declaring a primary key, which is clustered by default.

Does SELECT INTO create indexes automatically?

No. SELECT INTO copies only the data and column definitions. Indexes and constraints of the source table are not copied, so you need to create them separately:

SELECT SalesOrderID, CustomerID
INTO #Orders
FROM Sales.SalesOrderHeader;

CREATE CLUSTERED INDEX IX_Orders_SalesOrderID
ON #Orders (SalesOrderID);
Do indexes always improve temp table performance?

No. An index helps when the temp table is large and queried selectively or repeatedly. For small tables or tables read once in a full scan, the cost of creating the index can exceed the benefit. Compare logical reads and CPU time with and without the index to decide.