HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMajor

Select next and previous rows

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
rowspreviousnextandselect

Problem

I have the following table:

CREATE TABLE post (
  id            bigint primary key,
  thread_id     bigint,
  is_notice     boolean,
  title         text,
  content       text
)


I display the list using the following query:

SELECT * FROM post ORDER BY is_notice desc, thread_id desc, id


Then, given the post selected by id(i.e. SELECT * FROM post where id=3), how do I retrieve the next and previous posts?

Solution

Using PostgreSQL's Window Functions, specifically LAG and LEAD, should be able to show you the previous and next entries in your table.

select *
from (
    select  id, thread_id, is_notice, title, content,
            lag(id) over (order by is_notice desc, thread_id desc, id asc) as prev,
            lead(id) over (order by is_notice desc, thread_id desc, id asc) as next
    from post
    ) x
where 3 IN (id, prev, next);


A demo can be found here:
http://sqlfiddle.com/#!15/9fd7a/8

Code Snippets

select *
from (
    select  id, thread_id, is_notice, title, content,
            lag(id) over (order by is_notice desc, thread_id desc, id asc) as prev,
            lead(id) over (order by is_notice desc, thread_id desc, id asc) as next
    from post
    ) x
where 3 IN (id, prev, next);

Context

StackExchange Database Administrators Q#53862, answer score: 29

Revisions (0)

No revisions yet.