Sql-server – Indexing a temp table

indexsql servertemporary-tables

Would it be a good idea to apply indexing on temp tables when it is suggested to do so in the estimated execution plan?

Best Answer

Yes it is a good idea. Temp tables will benefit from indexes in the same way that permanent tables will. Index creation is the same, too, with a few minor exclusions.

The indexes function in the same way as they do on permanent tables, with the exception that temp tables are cached, which can hurt if the workloads are skewed significantly.

The same caveats apply too. Just because an index exists does not mean the optimizer will use it. Writes will be costlier with many indexes in place. Stale statistics can produce poor plans.

Recently I was able to reduce a large batch procedure's run time from over 20 minutes to under three by adding indexes to temp tables. This is a worthwhile task.

See also Indexing Temp Tables by Erik Darling.