X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id 7B9C152B98 for ; Wed, 13 Jul 2005 12:28:37 -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 69741-04 for ; Wed, 13 Jul 2005 15:28:35 +0000 (GMT) Received: from mail7.atl.registeredsite.com (mail7.atl.registeredsite.com [64.224.219.81]) by svr1.postgresql.org (Postfix) with ESMTP id 968CD52ABF for ; Wed, 13 Jul 2005 12:28:32 -0300 (ADT) Received: from hallsofworlds.com (ws0379.otak.com [216.122.57.125] (may be forged)) by mail7.atl.registeredsite.com (8.12.11/8.12.8) with ESMTP id j6DFSVJB027118 for ; Wed, 13 Jul 2005 15:28:31 GMT Received: from localhost (david@localhost) by hallsofworlds.com (8.11.6/8.11.0) with ESMTP id j6DFSUM26639 for ; Wed, 13 Jul 2005 15:28:31 GMT (envelope-from david@blankley.com) Date: Wed, 13 Jul 2005 15:28:29 +0000 (GMT) From: David Blankley X-X-Sender: david@hallsofworlds.com To: pgsql-sql@postgresql.org Subject: Dynamic Offset Determination Message-ID: <20050713151014.P23754-100000@hallsofworlds.com> MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.05 tagged_above=0 required=5 tests=FORGED_RCVD_HELO X-Spam-Level: X-Archive-Number: 200507/114 X-Sequence-Number: 22092 Problem Statement: I want to return n rows from a table. These n rows are relative to an offset. The part I can't figure out: The offset needs to be determined from values in the rows. Example: Given a table foo: CriteriaCol integer OrderedCol integer I can figure out the number of rows SELECT COUNT(CriteriaCol) FROM foo; How do I determine the offset? SELECT {rownum?} FROM foo WHERE CriteriaCol = SomeValidValue; With the rownum I can then determine the rows I want. SELECT * FROM foo ORDER BY OrderedCol LIMIT 21 OFFSET (rownum-10); Don't worry about boundary conditions, functions, etc, I can sort that out once I know how to get the offset. -------------------------- Searching the forums, the one potential hack I've found is: Quote from: http://archives.postgresql.org/pgsql-sql/2003-04/msg00287.php create temp sequence foo; select nextval('foo'), * from (select ... whatever ... order by something) ss; drop sequence foo; Presumably I would get my ordinal value from the sequence before dropping it. This seems like it would be a potentially slow process. Also, this solution dates to 2003, so I thought it worth asking in case a better solution has come along. Thanks for suggestions/solutions Dave