Re: grabbing id of previous and next record for current select

From: Michael Glaesemann <grzm(at)seespotcode(dot)net>
To: amiller(at)onlinebrands(dot)com
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: grabbing id of previous and next record for current select
Date: 2007-01-11 22:10:01
Message-ID: 477F374F-39D9-408E-B78D-7B04131DD72B@seespotcode.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice


On Jan 12, 2007, at 6:17 , Alan T. Miller wrote:

> When you select a record, you want to at the same time grab the id
> of the following record, as well as the id of the previous record.

> I know a kludge to get the next id, is to simply use the offset
> function in a second SQL statement in the following manner:
>
> SELECT id FROM table ORDER BY id ASC LIMIT 1 OFFSET ':current_id';

This won't necessarily work: offset is based on the number of rows,
not their id.

> The ideal solution would be the ability to issue one query and get
> all three results. Also, assuming I want the option of traversing
> these records from smallest ID to largest ID, and from the largest
> ID to the smallest ID.

Here's what I'd try:

SELECT *
FROM (
-- record with previous id, if exists
SELECT *
FROM foo
WHERE id < :current_id
ORDER BY id DESC
LIMIT 1
UNION
-- record with current_id, if exists
SELECT *
FROM foo
WHERE id = :current_id
UNION
-- record with next id, if exists
SELECT *
FROM foo
WHERE id > :current_id
ORDER BY id ASC
LIMIT 1
) maybe_three_records
ORDER BY id;

Michael Glaesemann
grzm seespotcode net

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Sven Sporer 2007-01-12 16:54:32 User Management, drop privilege
Previous Message Alan T. Miller 2007-01-11 21:17:35 grabbing id of previous and next record for current select