Re: Slow query: select * order by XXX desc offset 10 limit 10

From: Pavel Stehule <pavel(dot)stehule(at)gmail(dot)com>
To: Alexander Farber <alexander(dot)farber(at)gmail(dot)com>
Cc: pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: Slow query: select * order by XXX desc offset 10 limit 10
Date: 2011-10-14 09:40:14
Message-ID: CAFj8pRBK6bgXJLKir+PUf8_6TSE1FjLizrdC7XFcXdkKZNKh8g@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

2011/10/14 Alexander Farber <alexander(dot)farber(at)gmail(dot)com>:
> Thank you -
>
> On Fri, Oct 14, 2011 at 11:30 AM, Pavel Stehule <pavel(dot)stehule(at)gmail(dot)com> wrote:
>> you should to use a DECLARE statement
>> http://www.postgresql.org/docs/9.1/interactive/sql-declare.html
>> and fetch statement
>> http://www.postgresql.org/docs/9.1/interactive/sql-fetch.html
>
> I've managed to create a cursor
> and can fetch the data row by row:
>
> quincy=> start TRANSACTION;
> quincy=> declare XXX cursor for select to_char(qdatetime,
> 'YYYY-MM-DD') as
> QDATETIME,ID,NAME,CATEGORY,APPSVERSION,OSVERSION,DETAILS,DEVINFO from
> quincyview where qdatetime <= now() order by QDATETIME desc ;
> quincy=> fetch XXX;
> .....
> quincy=> fetch XXX;
> .....
>
> But how do I "go back"?
>
> For my jQuery HTML table (DataTables.net)
> I need to be able to go back and forth.
>
> Regards
> Alex

you can use a scrollable cursors.

BEGIN WORK;

-- Set up a cursor:
DECLARE liahona SCROLL CURSOR FOR SELECT * FROM films;

-- Fetch the first 5 rows in the cursor liahona:
FETCH FORWARD 5 FROM liahona;

code | title | did | date_prod | kind | len
-------+-------------------------+-----+------------+----------+-------
BL101 | The Third Man | 101 | 1949-12-23 | Drama | 01:44
BL102 | The African Queen | 101 | 1951-08-11 | Romantic | 01:43
JL201 | Une Femme est une Femme | 102 | 1961-03-12 | Romantic | 01:25
P_301 | Vertigo | 103 | 1958-11-14 | Action | 02:08
P_302 | Becket | 103 | 1964-02-03 | Drama | 02:28

-- Fetch the previous row:
FETCH PRIOR FROM liahona;

code | title | did | date_prod | kind | len
-------+---------+-----+------------+--------+-------
P_301 | Vertigo | 103 | 1958-11-14 | Action | 02:08

-- Close the cursor and end the transaction:
CLOSE liahona;
COMMIT WORK;

this example is from doc
http://www.postgresql.org/docs/9.1/interactive/sql-fetch.html

Regards

Pavel

>
> --
> Sent via pgsql-general mailing list (pgsql-general(at)postgresql(dot)org)
> To make changes to your subscription:
> http://www.postgresql.org/mailpref/pgsql-general
>

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Janning Vygen 2011-10-14 10:01:45 Client hangs in socket read
Previous Message Alexander Farber 2011-10-14 09:36:50 Re: Slow query: select * order by XXX desc offset 10 limit 10