X-Original-To: pgsql-performance-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id 3E76ED1CAF8 for ; Wed, 28 Jul 2004 00:33:18 -0300 (ADT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 07766-10 for ; Wed, 28 Jul 2004 03:33:12 +0000 (GMT) Received: from www.postgresql.com (www.postgresql.com [200.46.204.209]) by svr1.postgresql.org (Postfix) with ESMTP id 49F79D1BABE for ; Wed, 28 Jul 2004 00:22:49 -0300 (ADT) Received: from pillette.com (adsl-67-119-5-202.dsl.snfc21.pacbell.net [67.119.5.202]) by www.postgresql.com (Postfix) with ESMTP id 6AF40CF7409 for ; Tue, 27 Jul 2004 14:38:26 -0300 (ADT) Received: (from andrew@localhost) by pillette.com (8.11.6/8.11.6) id i6RHbOP04615; Tue, 27 Jul 2004 10:37:24 -0700 Date: Tue, 27 Jul 2004 10:37:24 -0700 From: andrew@pillette.com Message-Id: <200407271737.i6RHbOP04615@pillette.com> Subject: Re: best way to fetch next/prev record based on index To: "Merlin Moncure" Cc: X-Originating-IP: 192.168.1.203 X-Mailer: Webmin 0.940 MIME-Version: 1.0 X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.3 tagged_above=0.0 required=5.0 tests=NO_REAL_NAME X-Spam-Level: Content-Type: text/plain Content-Transfer-Encoding: 7bit X-Archive-Number: 200407/202 X-Sequence-Number: 7593 "Merlin Moncure" wrote .. [snip] > select * from t where > a >= a1 and > (a > a1 or b >= b1) and > (a > a1 or b > b1 or c > c1) I don't see why this is guaranteed to work without an ORDER BY clause, even if TABLE t is clustered on the correct index. Am I missing something? I have two suggestions: (1) I think I would have written SELECT * FROM t WHERE (a >= a1 AND b>=b1 AND c>=c1) ORDER BY a,b,c LIMIT 1 OFFSET 1; using the way LIMIT cuts down on sort time (I've never tried it with both LIMIT and OFFSET, though; you could always use LIMIT 2 and skip a record client-side if that works better). (2) I've seen code where depending on the types and values of the fields, it was possible to construct a string from a, b, c by some sort of concatenation where the index now agreed with the lexicographic (dictionary) ordering on the string. Postgres could do that with a functional index, if your values can be used with this trick.