Re: CASE/WHEN behavior with NULLS

Поиск
Список
Период
Сортировка
От David Johnston
Тема Re: CASE/WHEN behavior with NULLS
Дата
Msg-id CF7D0EF2-A09E-44F7-BE2E-5E6BBC1EE394@yahoo.com
обсуждение исходный текст
Ответ на Re: CASE/WHEN behavior with NULLS  (Tom Lane <tgl@sss.pgh.pa.us>)
Ответы Re: CASE/WHEN behavior with NULLS  (Chris Angelico <rosuav@gmail.com>)
Re: CASE/WHEN behavior with NULLS  (Tom Lane <tgl@sss.pgh.pa.us>)
Список pgsql-general
On Aug 31, 2012, at 21:52, Tom Lane <tgl@sss.pgh.pa.us> wrote:

> David Johnston <polobo@yahoo.com> writes:
>> On Aug 31, 2012, at 19:14, Thalis Kalfigkopoulos <tkalfigo@gmail.com> wrote:
>>> This didn't work as expected (the NULL's persisted):
>>> ...CASE sum(foo) WHEN NULL THEN 0 ELSE sum(foo) END...
>
>> Guessing this form effectively evaluates to
>> WHEN sum(foo) = NULL instead of IS NULL and thus the wrong answer:
>
> Yeah, I think that's right.
>
>> That said you might want to try
>> SUM(COALESCE(foo, 0))
>
> Actually I'd go with "COALESCE(SUM(foo), 0)" since that requires only
> one COALESCE operation, not one per row.
>
>

These are not equivalent if some values of foo are not-null and you want the sum of all non-null values while replacing
anynulls with zero.  So the decision depends on what and why you are summing.  

As an alternative for the original question the coalesce(sum(foo),0) form is indeed better.

David J.



В списке pgsql-general по дате отправления:

Предыдущее
От: Tom Lane
Дата:
Сообщение: Re: CASE/WHEN behavior with NULLS
Следующее
От: Chris Angelico
Дата:
Сообщение: Re: CASE/WHEN behavior with NULLS