Re: LIMIT within UNION? - Mailing list pgsql-sql

From Josh Berkus
Subject Re: LIMIT within UNION?
Date
Msg-id 200209121320.28318.josh@agliodbs.com
Whole thread Raw
In response to Re: LIMIT within UNION?  (Andrew Perrin <clists@perrin.socsci.unc.edu>)
Responses Re: LIMIT within UNION?  (Andrew Perrin <clists@perrin.socsci.unc.edu>)
List pgsql-sql
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 BerkusAglio Database SolutionsSan Francisco



pgsql-sql by date:

Previous
From: Tom Lane
Date:
Subject: Re: LIMIT within UNION?
Next
From: Joe Conway
Date:
Subject: Re: [GENERAL] Latitude / Longitude