Return a value if no rows are found in Microsoft tSQL

This is similar to Adam Robinson’s, but uses ISNULL instead of COUNT.

SELECT ISNULL(
(SELECT 1 FROM Sites S
WHERE S.Id = @SiteId and S.Status = 1 AND 
      (S.WebUserId = @WebUserId OR S.AllowUploads = 1)), 0)

If the inner query has a matching row, then 1 is returned. The outer query (with ISNULL) then returns this value of 1. If the inner query has no matching row, then it doesn’t return anything. The outer query treats this like a NULL, and so the ISNULL ends up returning 0.

Leave a Comment