Re: Last x records

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Richard Huxton" <dev(at)archonet(dot)com>
Cc: pgsql-general(at)postgresql(dot)org, "Matthias Teege" <matthias(at)mteege(dot)de>
Subject: Re: Last x records
Date: 2001-02-27 16:01:36
Message-ID: 29338.983289696@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

"Richard Huxton" <dev(at)archonet(dot)com> writes:
> From: "Matthias Teege" <matthias(at)mteege(dot)de>
>> is there any way to get the last x records of an query
>> result?

> Otherwise, the only thing that I can think of is to set up a view that does
> the LIMIT n on a DESC then sort ASC when selecting on that view - might
> work.

Not in 7.0.* or before --- there is just plain no way to get multiple
levels of sorting in a query. In 7.1 you can do it like this:

SELECT * FROM
(SELECT ... ORDER BY foo DESC LIMIT n) ss
ORDER BY foo;

A workaround in 7.0.* is to use a temp table:

SELECT ... INTO TEMP t1 ... ORDER BY foo DESC LIMIT n;
SELECT * FROM t1 ORDER BY foo;
DROP TABLE t1;

The extra sort step shouldn't affect the speed much as long as n is small.

regards, tom lane

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Joel Burton 2001-02-27 16:08:08 Re: Case sensitivity
Previous Message Tom Lane 2001-02-27 15:56:33 Re: Query precompilation?