Re: SELECT: retrieve only 2 rows next to known row

From: Bruno Wolff III <bruno(at)wolff(dot)to>
To: nikolay(at)samokhvalov(dot)com
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: SELECT: retrieve only 2 rows next to known row
Date: 2005-09-09 12:38:30
Message-ID: 20050909123830.GA12435@wolff.to
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Fri, Sep 09, 2005 at 16:23:00 +0400,
Nikolay Samokhvalov <samokhvalov(at)gmail(dot)com> wrote:
>
> I've encountered with following task. I have one SELECT statement with
> ORDER BY clause; and know, that result set for this SELECT contains
> row with ID = 1000 (just for example).
> I don't know the position of this row in result set, but I want to
> retrieve 2 rows that are next to this one.
>
>
> Any ways to solve this problem? Is it possible to make only one query?
> (at least with one row in result set - e.g., with the row _following_
> after my one)

You could search for the following and preceding rows of the row with an
id of 1000 by using the comparison field(s) of the row in a where clause.
You can use limit 1 for each of these two subselects and union the results.
You may need to add the ID to the order by clause if your current ordering
does not produce a unique order.

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 2005-09-09 14:37:00 Re: SELECT: retrieve only 2 rows next to known row
Previous Message Nikolay Samokhvalov 2005-09-09 12:23:00 SELECT: retrieve only 2 rows next to known row