ajay saini
ajay saini

Reputation: 337

How to implement pagination in nodejs + postgresql

I am novice in Node.js. I want to implement pagination in my Api writing in Node.js using express as a framework and Postgresql as database. I want to get the data in form of pagination.

Thanks in advance.

Upvotes: 12

Views: 13292

Answers (2)

gdr2409
gdr2409

Reputation: 29

You can use indexes on columns used for sorting in pagination. Instead of limit & offset you can use where condition on column values (unique values) for efficiency. I have created a post regarding this https://medium.com/@shikhar01.cse14/pagination-with-postgresql-18e0b89e0b1c

Upvotes: 1

Lazar Nikolov
Lazar Nikolov

Reputation: 1028

You can use LIMIT and OFFSET in order to get chunks of data from the database. You need 2 variables to do the pagination, page and itemsPerPage. You'd get the page variable from the route itself, for example /api/items/:page, and for the itemsPerPage, you can make it default 20 items for example, but allow the clients to specify it through a query ?items=50 or the request body or a header or however you want. Then when you have both variables you can perform the query on the database, like:

SELECT *
    FROM items
    LIMIT {itemsPerPage} OFFSET {(page - 1) * itemsPerPage}

LIMIT means retrieve me X number of items, OFFSET means skip Y items. Both of them combined would be: "skip Y items and get me the next X items". Page - 1 means if you're on the 1st page we don't want to skip any items, but retrieve the first X items. This is valid when the page number is >= 1.

Upvotes: 37

Related Questions