Cursor Pagination
PostgreSQL Optimize: Cursor Pagination
Categories:
Get the article list order by its score
Assume that we have an article table with the following structure
- id
- article_score
- status
id | article_score | status |
---|---|---|
1 | 30 | published |
2 | 21 | published |
3 | 16 | published |
4 | 10 | published |
5 | 30 | published |
6 | 6 | published |
7 | 9 | published |
8 | 30 | published |
9 | 26 | published |
10 | 30 | published |
The first page of the cursor pagination
We can order the article_score desc
to get the better score from the article. And set the limit to the 3
on the every page.
select *
from article
where status = 'published'
order by article_score desc, id asc
limit 3
id | article_score | status |
---|---|---|
1 | 30 | published |
5 | 30 | published |
8 | 30 | published |
10 | 30 | published |
9 | 26 | published |
2 | 21 | published |
3 | 16 | published |
4 | 10 | published |
7 | 9 | published |
6 | 6 | published |
The first page of the article that order by article_score desc
will get the following records.
id | article_score | status |
---|---|---|
1 | 30 | published |
5 | 30 | published |
8 | 30 | published |
Get the next page of the cursor pagination
The article_score
and id
of the last record on the first page are 30
and 8
. Then the next page of the article should be one of the following criteria:
article_score
less than30
article_score
equal to30
but theid
is greater then8
select *
from article
where ( article_score < 30 or (article_score = 30 and id > '8'))
and status = 'published'
order by article_score desc, id asc
limit 3
The next page of the article that order by article_score desc
will get the following records.
id | article_score | status |
---|---|---|
10 | 30 | published |
9 | 26 | published |
2 | 21 | published |