Which one do you guys think is more efficient (less load)?
SELECT t1.a,
(CASE
WHEN t1.p=1 THEN t2.g
WHEN t1.p=2 THEN t3.g
END) as v
FROM t1
LEFT JOIN t2 ON t1.x=t2.x
LEFT JOIN t3 ON t1.y=t3.y
OR
SELECT
t1.a, t2.v
FROM t1
outer apply (
SELECT v= CASE
WHEN t1.p=1 THEN (SELECT v FROM t2 WHERE t1.x=t2.x)
WHEN t1.p=2 THEN (SELECT v FROM t3 WHERE t1.y=t3.y)
END
) t2
Just want to figure out how sql engine works..
[What im trying to study in this question]
In first query the tables t2
andt3
will always be called, but in the 2nd query will they be only called if the case matches (and hence be less load = only 2 tables checked instead of 3 per row)?
I would go with the
left join
, but write this as:This logic is not necessarily exactly equivalent to your logic, but I suspect that this query does what you intend. (For instance, if
t2.g
is everNULL
andt1.p = 1
, then the results are not the same.)As for performance,
LEFT JOIN
gives the optimizer more options for the query than aCASE
expression does, so it is likely to be faster. However, with proper indexing, all three queries probably have good performance.