sibert sibert - 7 months ago 31
SQL Question

Which is most correct - coalesce(sum(value)) OR sum(coalesce(value))?

I have seen both on SO, but I wonder if there is a "best practice" or advantage to coalesce the sum before or after:

coalesce(sum(value),0) OR sum(coalesce(value),0)


Just curious...

hvd hvd
Answer

They don't do the same thing. Putting the COALESCE inside does not do anything if you have no records. Putting it outside changes the result in that case too to 0. Which to use depends on the result you want.