Skip site navigation (1) Skip section navigation (2)

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

From: Markus Schaber <schabios(at)logi-track(dot)com>
To: "Merlin Moncure" <merlin(dot)moncure(at)rcsonline(dot)com>
Cc: <pgsql-performance(at)postgresql(dot)org>
Subject: Re: best way to fetch next/prev record based on index
Date: 2004-07-27 14:13:25
Message-ID: (view raw, whole thread or download thread mbox)
Lists: pgsql-performance
Hi, Merlin,

On Tue, 27 Jul 2004 09:07:02 -0400
"Merlin Moncure" <merlin(dot)moncure(at)rcsonline(dot)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'

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(at)logi-track(dot)com |

In response to


pgsql-performance by date

Next:From: Christopher Kings-LynneDate: 2004-07-27 14:19:49
Subject: Re: Automagic tuning
Previous:From: Markus SchaberDate: 2004-07-27 13:15:31
Subject: Automagic tuning

Privacy Policy | About PostgreSQL
Copyright © 1996-2017 The PostgreSQL Global Development Group