Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do the order of JOINs make a difference?

Tags:

sql-server

Say I have a query like the one below:

SELECT t1.id, t1.Name
FROM Table1 as t1 --800,000 records
INNER JOIN Table2 as t2 --500,000 records
ON t1.fkID = t2.id
INNER JOIN Table3 as t3 -- 1,000 records
ON t1.OtherId = t3.id

Would i see a performance improvement if I changed the order of my joins on Table2 and Table3. See below:

SELECT t1.id, t1.Name
FROM Table1 as t1 --800,000 records
INNER JOIN Table3 as t3 -- 1,000 records
ON t1.OtherId = t3.id
INNER JOIN Table2 as t2 --500,000 records
ON t1.fkID = t2.id

I've heard that the Query Optimizer will try to determine the best order but doesn't always work. Does the version of SQL Server you are using make a difference?

like image 262
Abe Miessler Avatar asked Jan 28 '10 00:01

Abe Miessler


1 Answers

The order of joins makes no difference.

What does make a difference is ensuring your statistics are up to date.

One way to check your statistics is to run a query in SSMS and include the Actual execution plan. If the Estimated number of rows is very different to the Actual number of rows used by any part of the execution plan, then your statistics are out of date.

Statistics are rebuilt when the related indexes are rebuilt. If your production maintenance window allows, I would update statistics every night.

This will update statistics for all tables in a database:

exec sp_MSforeachtable "UPDATE STATISTICS ?"
like image 194
Mitch Wheat Avatar answered Sep 20 '22 12:09

Mitch Wheat