Re: null value in queries to default in zero

From: Scott Lamb <slamb(at)slamb(dot)org>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: null value in queries to default in zero
Date: 2002-11-15 17:39:53
Message-ID: 1037381994.2849.8.camel@apt.slamb.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Tue, 2002-11-12 at 07:49, Dorward Villaruz wrote:
> select to_char(avg(f1),'FM999999.99') from test where f2 > 7 will yield
> to_char
> --------
>
> (1 row)
>
> is their a way to make the value zero if the return is null?

Sure. The easiest way is:

select to_char(coalesce(avg(f1), 0), 'FM999999.99')
from test
where f2 > 7

You can also do:

select to_char(case when avg(f1) is not null then avg(f1)
else 0
end, 'FM999999.99')
from test
where f2 > 7

coalesce returns the first argument to it that is not null, or null if
they all are. It's actually implemented using the case one, which is
more verbose but more flexible.

Scott

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Garrett Bladow 2002-11-15 17:58:34 Re: Poor Performance on large Tables
Previous Message Scott Lamb 2002-11-15 17:34:41 Re: psql question