I have a question about perf of the following query:
DECLARE @detail_level INT = 1,
@DETAIL_1 INT = 1,
@DETAIL_2 INT = 2,
@DETAIL_3 INT = 4
SELECT mtbl.*,
CASE
WHEN @detail_level & @DETAIL_1 <> 0 THEN tbl_1.value
ELSE NULL
END,
CASE
WHEN @detail_level & @DETAIL_2 <> 0 THEN tbl_2.value
ELSE NULL
END,
CASE
WHEN @detail_level & @DETAIL_3 <> 0 THEN tbl_3.value
ELSE NULL
END
FROM mtbl
LEFT OUTER JOIN tbl_1
ON @detail_level & @DETAIL_1 <> 0
AND mtbl.KEY = tbl_1.KEY
LEFT OUTER JOIN tbl_2
ON @detail_level & @DETAIL_2 <> 0
AND mtbl.KEY = tbl_2.KEY
LEFT OUTER JOIN tbl_3
ON @detail_level & @DETAIL_3 <> 0
AND mtbl.KEY = tbl_3.KEY
WHERE mtbl.KEY = @something
Will the query engine optimize the query by using the detail level filter to avoid unnecessary table join and unnecessary table row access for those detail table columns?
If yes, will query engine even not acquire index locks for those unnecessary table?
I captured the query plan in SQL Server 2008 and index search operations still existed even detail level did not match. But the query with less details did (~ 30%) faster than the one with full details (data volumn ~ 500,000).