Re: division by zero error in a request

From: "Karen Hill" <karen_hill22(at)yahoo(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: division by zero error in a request
Date: 2006-10-18 18:50:32
Message-ID: 1161197432.411766.180770@i42g2000cwa.googlegroups.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


Bernard Grosperrin wrote:
> I wants to make a view giving me some statistics.
>
> I am not sure to understand why something like this
>
> SELECT location_id, (sold_parts_amount_dly + sold_labor_amount_dly) /
> (sold_parts_amount_dly + sold_labor_amount_dly) from sales
>
> give me a division by zero error?
>
> If that is not the way to go, should I write a function that I would call
> instead?
>
> Thanks,
> Bernard

Hi Bernard,

In mathematics, you cannot divide by zero. So 4/0 is not possible for
example. In your SELECT query, sold_parts_amount_dly and
sold_labor_amunt_dly are zero in some cases, giving you the division by
zero error.

You could solve this by using CASE.
http://www.postgresql.org/docs/8.1/static/functions-conditional.html

Or you could create a pl/pgsql function that 1.) either uses exceptions
to handle the division by zero error or 2.) check that
sold_parts_amount_dly and sold_labor_amount_dly are not zero before
dividing by them within a function.

The simplest would be to use CASE in your query.

regards,
karen

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Alvaro Herrera 2006-10-18 19:00:50 Re: [HACKERS] query log corrupted-looking entries
Previous Message Ilja Golshtein 2006-10-18 18:45:53 Re: COPY FROM STDIN instead of INSERT