Optimisation Fun

Since I have absolutely no life, one of my greatest joys is making code go faster; especially SQL queries.
 
Did a good one this morning. A query that was taking about 20s to run is now taking 3s. The trick in this case was to change the stored procedure to build a list of affected data first in a table variable and then to join to that table in a second query.
 
You’d think that this would be slowed because SQL Server’s wonderful optimiser would be able to sort things out all in one query, but it’s not always the case. Damned if I know why.
 
Of course, it means you end up with horrible multi-part queries that nobody can understand, but that’s their problem.

What I had

SELECT stuff
FROM table1
INNER JOIN table2 ON things
INNER JOIN …..
INNER JOIN table7 ON OtherThings
WHERE (a long list of things)

What I have Now

DECLARE @MyTable TABLE AS (fields)

INSERT INTO @MyTable
SELECT fields
FROM table1
INNER JOIN table2
WHERE (one or two things)

SELECT fields
FROM @MyTable
INNER JOIN table3 ON things
INNER JOIN table ….
INNER JOIN table7 ON OtherThings
WHERE (a shorter but still substantial list of things)

 

I guess it goes to show that there’s no substitute in SQL (at the moment) for staring at execution plans and then mucking about.

Advertisements
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s