Advertisement
Intermediate SQL Server, Temporary Tables & Table Variables

Can you create indexes on a temporary table, and how does this compare to indexing options available for table variables?

Short answer

Yes, you can create additional indexes on a local or global temporary table after creating it, just like a regular permanent table, giving you the ability to optimize queries against larger intermediate data sets, while table variables in most versions have historically been…

Save SQL Server mock interview
Advertisement
AModel answer
Yes, you can create additional indexes on a local or global temporary table after creating it, just like a regular permanent table, giving you the ability to optimize queries against larger intermediate data sets, while table variables in most versions have historically been much more limited in this regard, typically only supporting a primary key or unique constraint defined inline during declaration.
CREATE TABLE #TempOrders (OrderId INT, CustomerId INT, Amount DECIMAL(10,2));
CREATE INDEX IX_TempOrders_CustomerId ON #TempOrders(CustomerId);
Real-world example
A complex reporting procedure creates an additional index on a temporary table holding a large intermediate result set, significantly speeding up subsequent queries that filter and join against that temporary data by customer.
Likely follow-ups
  • Does creating an index on a temporary table add meaningful overhead for very small data sets?
  • What indexing options, if any, are available directly within a table variable's declaration?
Related topics