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
 General SQL Server Forums
 New to SQL Server Programming
 Speed Issue

Author  Topic 

atulkamat2008
Starting Member

1 Post

Posted - 2008-06-23 : 06:04:59
Hello all

I am running a query where the same table is join 4 times. Due to this number of records goes to millions. It take more than 5 min for the query to run. I am trying to optimize the query.
Anybody please help me in the regards

Thank You

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-06-23 : 06:20:02
1) Add missing important indexes
2) Avoid doing calculations over the indexes columns
3) Only return the records you really want
4) Make the 4 JOINs to same table as a crosstab/pivot, if possible.

Try these first. If you are not satisfied, please post full query used here and maybe we can spot something more.



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-06-23 : 06:37:50
quote:
Originally posted by atulkamat2008

Hello all

I am running a query where the same table is join 4 times. Due to this number of records goes to millions. It take more than 5 min for the query to run. I am trying to optimize the query.
Anybody please help me in the regards

Thank You


It would be better if you could give some information about your reuirement so that we may suggest if there are some better approaches for achieving the same.
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-06-23 : 06:54:09
Instead of joining same table four times like this
...
LEFT JOIN Telephone AS t1 ON t1.CustomerID = c.CustomerID
AND t1.Type = 'Home'
LEFT JOIN Telephone AS t2 ON t2.CustomerID = c.CustomerID
AND t2.Type = 'Work'
LEFT JOIN Telephone AS t3 ON t3.CustomerID = c.CustomerID
AND t3.Type = 'Mobile'
LEFT JOIN Telephone AS t4 ON t4.CustomerID = c.CustomerID
AND t4.Type = 'Fax'
You can write like this and only join the table once.
...
LEFT JOIN (

SELECT CustomerID,
MAX(CASE WHEN Type = 'Home' THEN Phone ELSE NULL END) AS Home,
MAX(CASE WHEN Type = 'Work' THEN Phone ELSE NULL END) AS Work,
MAX(CASE WHEN Type = 'Mobile' THEN Phone ELSE NULL END) AS Mobile,
MAX(CASE WHEN Type = 'Fax' THEN Phone ELSE NULL END) AS Fax
GROUP BY CustomerID
) AS t ON t.CustomerID = c.CustomerID



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-06-23 : 07:04:52
or even use PIVOT operator if you're using SQL 2005 with compatibility level 90.
Go to Top of Page
   

- Advertisement -