For an empty rowset, coalesce
won't be invoked:
(select top 1 coalesce(Id, 0) from ...)
And an empty rowset in a scalar context returns null
:
select (select 1 where 1=0)
-->
NULL
One solution is to move the coalesce
outside the subquery:
coalesce((select top 1 Id from ...),0)