DEV Community

Discussion on: Offset and Cursor Pagination explained

Collapse
 
tejaswipandava profile image
tejaswipandava • Edited

Thank you, this has cleared my doubt. Can you attach the implementation for them in SQL. It would be great.
Implementation of Offset Pagination (very basic)
SELECT * from ourTable LIMIT offsetValue , limitValue;
offsetValue specifies number of records to skip.
limitValues specifies number of records to return.

Implementation of CursorPagination (very basic):
SELECT * from ourTable where id<=cursor order by id desc LIMIT limitValue
cursor needs to be returned by the client

Collapse
 
jackmarchant profile image
Jack Marchant

The SQL you have is very close:

Offset
select * from posts LIMIT 20 offset 20;
If you were to paginate every 20 results, then offset would increase/decrease by 20 each subsequent query.

Cursor
select * from posts where id < 40 LIMIT 20;
The cursor is id here, but it could be any column, even a dedicated cursor.

Hope that helps.

Collapse
 
dheerajpande profile image
Dheeraj • Edited

for the cursor query

select * from posts where id < 40 LIMIT 20;

how can we guarantee which 20 to pick?

like lets say that there are 40 records with id 1 to 40,

if I am doing "prev" with id "40" I should get id 20 to 39.

With that be the case here?