I am having big time differences in my query, and it seems that the order in which the connection occurs (inner and left outer) in the query makes a difference. Are there any “basic rules" in what order should the connections be?
Both of them are part of a big request. The difference between the two is that the left join is placed last in a faster request.
Slow request: (> 10 minutes)
SELECT [t0].[Ref], [t1].[Key], [t1].[Name], (CASE WHEN [t3].[test] IS NULL THEN CONVERT(NVarChar(250),@p0) ELSE CONVERT(NVarChar(250),[t3].[Key]) END) AS [value], (CASE WHEN 0 = 1 THEN CONVERT(NVarChar(250),@p1) ELSE CONVERT(NVarChar(250),[t4].[Key]) END) AS [value2] FROM [dbo].[tblA] AS [t0] INNER JOIN [dbo].[tblB] AS [t1] ON [t0].[RefB] = [t1].[Ref] LEFT OUTER JOIN ( SELECT 1 AS [test], [t2].[Ref], [t2].[Key] FROM [dbo].[tblC] AS [t2] ) AS [t3] ON [t0].[RefC] = ([t3].[Ref]) INNER JOIN [dbo].[tblD] AS [t4] ON [t0].[RefD] = ([t4].[Ref])
Faster request: (~ 30 seconds)
SELECT [t0].[Ref], [t1].[Key], [t1].[Name], (CASE WHEN [t3].[test] IS NULL THEN CONVERT(NVarChar(250),@p0) ELSE CONVERT(NVarChar(250),[t3].[Key]) END) AS [value], (CASE WHEN 0 = 1 THEN CONVERT(NVarChar(250),@p1) ELSE CONVERT(NVarChar(250),[t4].[Key]) END) AS [value2] FROM [dbo].[tblA] AS [t0] INNER JOIN [dbo].[tblB] AS [t1] ON [t0].[RefB] = [t1].[Ref] INNER JOIN [dbo].[tblD] AS [t4] ON [t0].[RefD] = ([t4].[Ref]) LEFT OUTER JOIN ( SELECT 1 AS [test], [t2].[Ref], [t2].[Key] FROM [dbo].[tblC] AS [t2] ) AS [t3] ON [t0].[RefC] = ([t3].[Ref])
source share