patternsqlMajor
Select next and previous rows
Viewed 0 times
rowspreviousnextandselect
Problem
I have the following table:
I display the list using the following query:
Then, given the post selected by id(i.e.
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, idThen, 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
A demo can be found here:
http://sqlfiddle.com/#!15/9fd7a/8
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.