Re: returning count(*) when it is > 1, else -1

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Richard Huxton <dev(at)archonet(dot)com>
Cc: Gerardo Herzig <gherzig(at)fmed(dot)uba(dot)ar>, postgres list <pgsql-sql(at)postgresql(dot)org>
Subject: Re: returning count(*) when it is > 1, else -1
Date: 2008-10-17 12:32:32
Message-ID: 14252.1224246752@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Richard Huxton <dev(at)archonet(dot)com> writes:
> SELECT
> CASE WHEN total >0 THEN total ELSE -1 END AS new_total
> FROM (
> SELECT count(*) AS total FROM test WHERE id=$1
> ) AS raw_total

Actually you could just do

SELECT
CASE WHEN count(*) >0 THEN count(*) ELSE -1 END AS total
FROM test WHERE id=$1;

PG has avoided redundant calculations of duplicate aggregates for some
time. (This doesn't help in the original formulation because it
actually had two different sub-selects; the case that is handled is
identical aggregate expressions within SELECT list or HAVING of a single
SELECT.)

regards, tom lane

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Gerardo Herzig 2008-10-17 12:50:26 Re: returning count(*) when it is > 1, else -1
Previous Message Achilleas Mantzios 2008-10-17 12:28:59 Re: returning count(*) when it is > 1, else -1