简体   繁体   中英

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...

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.

The SQL engine will probably optimize this anyway but using

coalesce(sum(value),0) 

may be a bit faster because the summing can be done without the need to process a function and at the end coalesce is called one time .

The secone version calls coalesce for every record and sets the value to 0 if there are null values in the summing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM