Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best use of indices on temporary tables in T-SQL

If you're creating a temporary table within a stored procedure and want to add an index or two on it, to improve the performance of any additional statements made against it, what is the best approach? Sybase says this:

"the table must contain data when the index is created. If you create the temporary table and create the index on an empty table, Adaptive Server does not create column statistics such as histograms and densities. If you insert data rows after creating the index, the optimizer has incomplete statistics."

but recently a colleague mentioned that if I create the temp table and indices in a different stored procedure to the one which actually uses the temporary table, then Adaptive Server optimiser will be able to make use of them.

On the whole, I'm not a big fan of wrapper procedures that add little value, so I've not actually got around to testing this, but I thought I'd put the question out there, to see if anyone had any other approaches or advice?

like image 883
ninesided Avatar asked Sep 10 '08 10:09

ninesided


People also ask

Should I create indexes on temp tables?

Adding indexes to the SQL temp tables will enhance its performance if the index is chosen correctly, otherwise, it can cause performance degradation.

Can we use index on temporary table in SQL Server?

You already know that your temp table needs an index. Let's say there's some query plan ouchie from not adding one. You've already realized that you should probably use a clustered index rather than a nonclustered index.

What is the main reason for adding indexes to tables?

Indexes are used to retrieve data from the database more quickly than otherwise. The users cannot see the indexes, they are just used to speed up searches/queries. Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update).


1 Answers

A few thoughts:

  • If your temporary table is so big that you have to index it, then is there a better way to solve the problem?
  • You can force it to use the index (if you are sure that the index is the correct way to access the table) by giving an optimiser hint, of the form:

    SELECT * 
    FROM   #table (index idIndex) 
    WHERE  id = @id
    

If you are interested in performance tips in general, I've answered a couple of other questions about that at some length here:

  • Favourite performance tuning tricks
  • How do you optimize tables for specific queries?
like image 150
AJ. Avatar answered Sep 24 '22 12:09

AJ.