The first problem is that these two queries do not have the same meaning and can return different results. The first query will only produce DocumentRoute
rows where Status = 1
. The second query will produce all DocumentRoute
rows, and where the Status
is null or is not equal to 1, will not perform the join to Routes
.
The second problem is that if you are just selecting columns from the Projects table using DISTINCT
, the LEFT JOIN
s can't possibly change the query in any way--so you may as well remove them.
Finally, without giving us some idea of the execution plan for both queries, and possibly some more details about the structure of the tables involved, no one is going to be able to definitively give you an answer about what is going on. Furthermore, the execution plan within your environment (where it takes 2 seconds) is not going to be helpful. We have to know the execution plan in the environment where it is running slowly.
To get an execution plan, run SET STATISTICS XML ON;
first, run the desired query, and see the execution plan shown in a result set given after the result set of the query itself.
Some thoughts on what could be causing the problem:
- Are statistics set to update automatically? If not, the server could choose a poor plan.
- What is the fragmentation of the tables involved in the query?
- Does the client database server have its tempdb files set up properly--if there is more than one, are they all the same size?