Dynamic Offset Determination

From: David Blankley <david(at)blankley(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Dynamic Offset Determination
Date: 2005-07-13 15:28:29
Message-ID: 20050713151014.P23754-100000@hallsofworlds.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

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

Browse pgsql-sql by date

  From Date Subject
Next Message David Blankley 2005-07-13 16:06:35 Re: Dynamic Offset Determination
Previous Message Jim Buttafuoco 2005-07-13 13:22:32 Re: Generating a range of integers in a query