From: Markus Schaber <schabios@logi-track.com>
To: Merlin Moncure <merlin.moncure@rcsonline.com>
Cc: pgsql-performance@postgresql.org
Subject: Re: best way to fetch next/prev record based on index
Date: Tue, 27 Jul 2004 16:13:25 +0200
Message-ID: <20040727161325.213b11eb@kingfisher.intern.logi-track.com> (raw)
In-Reply-To: <6EE64EF3AB31D5448D0007DD34EEB34101AEF5@Herge.rcsinc.local>
References: <6EE64EF3AB31D5448D0007DD34EEB34101AEF5@Herge.rcsinc.local>
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
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-performance@postgresql.org
Cc: schabios@logi-track.com, merlin.moncure@rcsonline.com
Subject: Re: best way to fetch next/prev record based on index
In-Reply-To: <20040727161325.213b11eb@kingfisher.intern.logi-track.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox