Re: LIMIT within UNION?

From: Andrew Perrin <clists(at)perrin(dot)socsci(dot)unc(dot)edu>
To: Josh Berkus <josh(at)agliodbs(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: LIMIT within UNION?
Date: 2002-09-13 15:45:10
Message-ID: Pine.LNX.4.21.0209131144580.32000-100000@perrin.socsci.unc.edu
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

This is certainly the most elegant solution - thanks!

Andy

----------------------------------------------------------------------
Andrew J Perrin - http://www.unc.edu/~aperrin
Assistant Professor of Sociology, U of North Carolina, Chapel Hill
clists(at)perrin(dot)socsci(dot)unc(dot)edu * andrew_perrin (at) unc.edu

On Thu, 12 Sep 2002, Josh Berkus wrote:

> Andrew,
>
> Another approach, one that does not require you to know before constructing
> the query how many eligible subjects there are, is not to use a union at all:
>
> SELECT * FROM (
> SELECT ... , zip
> FROM participants
> WHERE (typenr = 1 and <eligibility criteria)
> OR (typenr = 2)
> ORDER BY (typenr = 1 and <eligibility criteria>) DESC
> LIMIT 200 ) p1
> ORDER BY zip;
>
> The inner query gives you all of the records that meet the eligibility
> criteria, plus all of the records that have typenr = 2, in the order of
> whether or not they meet the criteria (as a boolean value) and truncates it
> at 200 records.
> The outer query then re-sorts this result in zip order.
>
> This seems, to me, much more flexible than using a UNION query.
>
> --
> -Josh Berkus
> Aglio Database Solutions
> San Francisco
>
>
> ---------------------------(end of broadcast)---------------------------
> TIP 6: Have you searched our list archives?
>
> http://archives.postgresql.org
>

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Josh Berkus 2002-09-13 17:51:41 Re: Assignments in PL/pgSQL
Previous Message Jean-Luc Lachance 2002-09-13 15:39:13 Re: sql group by statement