Re: selects on differing subsets of a query

From: Markus Schaber <schabi(at)logix-tt(dot)com>
To: ed(dot)temp(dot)01(at)gmail(dot)com
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: selects on differing subsets of a query
Date: 2006-05-03 10:40:01
Message-ID: 44588881.5070202@logix-tt.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Hi, Ed Temp,

ed(dot)temp(dot)01(at)gmail(dot)com wrote:

> First post, be gentle as I have terminology problems and so the
> subject might be wrongly worded.

Hmm, the biggest mistake seems that "et temp 01" is a very unlikely real
name, so you should reconfigure your mail client :-)

> What I am trying to construct is a *single* query showing the total
> number of males in the table
> and also the total number of male vegetarians in the table, i.e. the
> 2nd value is computed on a subset of the records needed for the first
> value.
>
> As 2 queries this would be:
> select count(*) from mytab where gender='m'
> select count(*) from mytab where gender='m' and diet_pref='veg'

Have you tried to UNION ALL the two queries?

> The table is big and I'd like to do the select where gender='m' only
> once. (In the actual situation the select is on a date range)

SELECT count(*),diet_pref='veg' FROM table WHERE gender='m' GROUP BY
diet_pref='veg'

Is not exactly what you want, as your application still has to add two
numbers to get the total result, but avoids the duplicated table scan.

SELECT count(*),count(nullif(diet_pref='veg', f)) FROM table WHERE
gender='m'

Should also give you both counts, this time in different columns, also
avoiding the duplicated table scan. It relies on the fact that
count(something) is only called if something is not null, whereas
count(*) is called for every row (as a special case).

HTH,
Markus

--
Markus Schaber | Logical Tracking&Tracing International AG
Dipl. Inf. | Software Development GIS

Fight against software patents in EU! www.ffii.org www.nosoftwarepatents.org

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message ed.temp.01 2006-05-03 11:16:42 Re: selects on differing subsets of a query
Previous Message ed.temp.01 2006-05-03 08:47:49 selects on differing subsets of a query