First, if you are going to use a subquery with a NULL
check, then use ISNULL()
. Note that I much, much, much prefer the ANSI standard coalesce()
, but SQL Server has done us the favor of documenting why ISNULL()
is better (effort that IMHO could have been spent fixing the problem):
For example, when the code COALESCE((subquery), 1) is executed, the subquery is evaluated twice.
Second, I don't think your sample code will work. You need an additional set of parentheses around the subquery.
And third, onto your question. With the right indexes, it is quite possible that the subquery method will perform better. In fact, the aggregation method has a weakness: the aggregate values are computed before the where
clause. This can mean that all the aggregate values are computed when very, very few are needed.
So, your construct is fine. If looking up a value took a lot of time, then you could also write this using APPLY
. That probably isn't necessary, though.