Skip to content
Advertisement

Joining Temp Tables Using Indexes

I’m just beginning to learn about INDEX and I’ve heard it could speed up results but my testing is having the opposite effect.

Some points about the data:

  • My company uses a SQL Server but I don’t know much else beyond that
  • I’m just an employee and don’t have any sort of admin access and am even restricted to seeing into some folders
  • #TABLE1 contains over 23,000 lines and runs in 1 second
  • #TABLE2 contains over 3.1M lines and runs in about 1.5 minutes
  • Using a join takes about 1.75 to 2.5 minutes
  • My attempt as using INDEX takes 2.5 to 3 or more
  • There are more tables I’ll be joining afterwards but these 2 are essentially the foundation for everything else

The query I tried below takes longer than if I did a normal JOIN

Am I doing something wrong that’s causing it to go slower?

Advertisement

Answer

You need a primary key on your temp tables with unique values to use as a CLUSTERED INDEX. Then you only need one other NONCLUSTERED INDEX on the JOIN columns. Assuming ID in #TABLE1 is unique, create your indexes like so:

Ditto for #TABLE2, again assuming ID id unique:

However, this may not solve your performance issue, if the actual bottleneck is the non-temp tables. You should run the SELECT portions of your script separately. If they are performing well on their own, then try these indexes. If not, then you need to speak to your DBA and find out why the SELECT is running slow.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement