Skip site navigation (1) Skip section navigation (2)

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 (view raw or flat)
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

pgsql-sql by date

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

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group