Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Query much faster using temp vs. derived table

Author  Topic 

malachi151
Posting Yak Master

152 Posts

Posted - 2012-08-24 : 17:34:55
I've noticed this several times and still don't fully understand it.

In cases where I have a complex derived table joined to another table it's often faster to load the derived table into a temp table then join to the temp table, instead of using a subquery. Why is this?

For example:


SELECT
A, B, C, X, Y, R
FROM
TableA ta
LEFT JOIN
(
SELECT X, Y, ROW_NUMBER() OVER (PARTITION BY X, Y ORDER BY Q, SUM(Z)) as R FROM TableB WHERE D = 4 GROUP BY X, Y
) tb ON ta.X = tb.X AND ta.Y = tb.Y
WHERE
A = 10


Such code may take a minute to run or more, but if I do the following:



SELECT X, Y, ROW_NUMBER() OVER (PARTITION BY X, Y ORDER BY Q, SUM(Z)) as R
INTO #temp
FROM TableB
WHERE D = 4 GROUP BY X, Y;

ALTER TABLE #temp ADD CONSTRAINT PK_temp(X,Y);

SELECT
A, B, C, X, Y, R
FROM
TableA ta
LEFT JOIN #temp tb ON ta.X = tb.X AND ta.Y = tb.Y
WHERE
A = 10


It runs in 0 seconds.

Why?

--------------------------------------------------
My blog: http://practicaltsql.net/
Twitter: @RGPSoftware

chadmat
The Chadinator

1974 Posts

Posted - 2012-08-24 : 17:50:25
Because you have an index on the temp table. How many rows are we talking about.

-Chad
Go to Top of Page

malachi151
Posting Yak Master

152 Posts

Posted - 2012-08-24 : 17:52:05
quote:
Originally posted by chadmat

Because you have an index on the temp table. How many rows are we talking about.

-Chad



No, the other tables have appropriate indexes as well.

Number of rows is typically 10K-100K.

--------------------------------------------------
My blog: http://practicaltsql.net/
Twitter: @RGPSoftware
Go to Top of Page

jackv
Master Smack Fu Yak Hacker

2179 Posts

Posted - 2012-08-25 : 02:34:28
Are you clearing down the BUFFER and CACHE in between the queries?
What do the Execution Plans say?

Jack Vamvas
--------------------
http://www.sqlserver-dba.com
Go to Top of Page

Jeff Moden
Aged Yak Warrior

652 Posts

Posted - 2012-08-25 : 21:09:11
I can't tell without the execution plan but I suspect that the derived table is being recalculated for every row of the Left Table. Look for large rowcounts in the execution plan to confirm or refute this possibility.


--Jeff Moden
Go to Top of Page
   

- Advertisement -