Re: coalesce and aggregate functions

From: "Kevin Grittner" <Kevin(dot)Grittner(at)wicourts(dot)gov>
To: "Patrick Welche" <prlw1(at)newn(dot)cam(dot)ac(dot)uk>, <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: coalesce and aggregate functions
Date: 2006-12-12 15:35:26
Message-ID: 457E77DE.EE98.0025.0@wicourts.gov
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

COALESCE returns the leftmost non-null value. Perhaps what you wanted
was sum(coalesce(b,0)) instead of coalesce(0,sum(b))

>>> On Tue, Dec 12, 2006 at 9:22 AM, in message
<20061212152219(dot)GC290(at)quartz(dot)itdept(dot)newn(dot)cam(dot)ac(dot)uk>, Patrick Welche
<prlw1(at)newn(dot)cam(dot)ac(dot)uk> wrote:
> Is this a bug, or don't I understand coalesce()?
>
> create table test (a int, b int);
> insert into test values (1,null);
> insert into test values (2,1);
> insert into test values (2,2);
> select * from test; -- returns:
> select sum(b) from test where a=1; -- null
> select sum(b) from test where a=2; -- 3
> select coalesce(0,sum(b)) from test where a=1; -- 0
> select coalesce(0,sum(b)) from test where a=2; -- 0
> delete from test where a=1;
> select coalesce(0,sum(b)) from test where a=2; -- 0 !
>
> So when I use coalesce() with sum(), I always get the constant. I
would
> have expected it only in the case where sum() returns null..
>
> What am I missing?

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Albe Laurenz 2006-12-12 15:42:50 Re: unixware and --with-ldap
Previous Message Gregory Stark 2006-12-12 15:35:07 Re: coalesce and aggregate functions