Fetching last n records from Posgresql

From: "Deole, Pushkar (Pushkar)" <pdeole(at)avaya(dot)com>
To: "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org>
Subject: Fetching last n records from Posgresql
Date: 2016-03-30 06:40:42
Message-ID: 78A4D6BFBAA5BA49A5E94DA00A6A76E3098643FC@AZ-FFEXMB04.global.avaya.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi,

Does PostgreSQL support a query to fetch last 'n' records that match the selection criteria. I am trying to fetch records from a table with start date that falls in last 30 days, however, I want to fetch the oldest 'n' records and not the recent ones. I know there is a LIMIT clause which I can use but it will fetch the first 'n' records.
I came across an approach which says that I can reverse the order and then use LIMIT and then order the records back using timestamp as below, but looking at the execution plan, it has to do a sort twice which may affect the performance of query if 'n' is large number:

WITH t AS (
SELECT * FROM mytable ORDER BY record_date ASC LIMIT 5
)
SELECT * FROM t ORDER BY record_date DESC;

Any thoughts/opinions?

Thanks,
Pushkar

Responses

Browse pgsql-general by date

  From Date Subject
Next Message John R Pierce 2016-03-30 07:08:00 Re: Fetching last n records from Posgresql
Previous Message David G. Johnston 2016-03-30 02:56:16 Re: pg_restore casts check constraints differently