Обсуждение: query to do a backward 'skip', possible with (index) optimization ?

Поиск
Список
Период
Сортировка

query to do a backward 'skip', possible with (index) optimization ?

От
"Albert Loo"
Дата:
hi,

Coming from xbase background and having just started on sql, I tried sql 
queries that does xbase 'skip'. I wanted to implement record browsing with 
'Next' and 'Previous' features. Currently, I'm testing this with a table of 
about 20,000 rows using psql.

I'm able to perform 'forward skip' query with :

=> select * from mytable where id > '12345' order by id limit 1;

- which returned what I wanted, 1 record with id value '12346'. Indexing on 
id further optimised the query.

However, I'm unable to optimise query when doing a 'backward skip'. I've 
tried :

=> select * from mytable where id < '12345' order by id desc limit 1;

- which returned the correct result '12344', but without optimization.

I was hoping a descending order index key would optimise it, but I think 
postgresql don't support it (yet ?).

Next, I tried using offset -1...which is not possible either :)

=> select * from mytable where id > '12345' order by id limit 1 offset -1;
ERROR:  parser: parse error at or near "-"

Has anyone tried 'backward skip' with optimization ?

______________________________________________________
Get Your Private, Free Email at http://www.hotmail.com



Re: [SQL] query to do a backward 'skip', possible with (index) optimization ?

От
Tom Lane
Дата:
"Albert Loo" <albertsql@hotmail.com> writes:
> => select * from mytable where id < '12345' order by id desc limit 1;

> - which returned the correct result '12344', but without optimization.

6.5.* doesn't know how to do that using an index (but 7.0 will).  I seem
to recall that someone posted a patch that partially solved the problem
in 6.5.* sources; check the archives if you are in a hurry.

BTW, I think you're probably going at this the wrong way, because it
doesn't extend to the case of fetching the *next* record in a
prespecified query.  You probably want to use DECLARE CURSOR and FETCH.
        regards, tom lane