Re: best way to fetch next/prev record based on index

Поиск
Список
Период
Сортировка
От Markus Schaber
Тема Re: best way to fetch next/prev record based on index
Дата
Msg-id 20040727161325.213b11eb@kingfisher.intern.logi-track.com
обсуждение исходный текст
Ответ на best way to fetch next/prev record based on index  ("Merlin Moncure" <merlin.moncure@rcsonline.com>)
Ответы Correction of best way to fetch next/prev record based on index  (Markus Schaber <schabios@logi-track.com>)
Список pgsql-performance
Hi, Merlin,

On Tue, 27 Jul 2004 09:07:02 -0400
"Merlin Moncure" <merlin.moncure@rcsonline.com> wrote:

> So, for a table t with a three part key over columns a,b,c, the query
> to read the next value from t for given values a1, b1, c1 is
>
> select * from t where
>     a >= a1 and
>      (a >  a1 or b >= b1) and
>      (a >  a1 or b > b1 or c > c1)

You mut not rely on such trickery to get any ordering, as the SQL data
model contains no ordering, and a query optimizer is free to deliver you
the tuples in any order it feels like.

Why don't you add a 'ORDER BY a,b,c ASC' to your query?

> Interestingly, it is possible to rewrite the above query by switching
> and with or and >= with >.  However when written that way, the planner
> almost never gets it right.

That's the reason why you cannot rely on any implicit ordering, the
planner is free to rewrite a query as it likes as long as it delivers
the same tuples, but in any order it wants.

> My problem is deceptively simple: how you read the next record from a
> table based on a given set of values?  In practice, this is difficult
> to implement.  If anybody can suggest a alternative/better way to
> this, I'm all ears.

So you really want something like

'SELECT * FROM t WHERE a>=a1 AND b>=b1 AND c>=c1 ORDER BY a,b,c ASC LIMIT 1'


HTH,
Markus
--
markus schaber | dipl. informatiker
logi-track ag | rennweg 14-16 | ch 8001 zürich
phone +41-43-888 62 52 | fax +41-43-888 62 53
mailto:schabios@logi-track.com | www.logi-track.com

В списке pgsql-performance по дате отправления:

Предыдущее
От: Tom Lane
Дата:
Сообщение: Re: best way to fetch next/prev record based on index
Следующее
От: Rod Taylor
Дата:
Сообщение: Re: best way to fetch next/prev record based on index