HomeAbout

Pagination

Offset Pagination

skip is the number of items to skip a certain number of records.

take is the number of items to select a limited range of records.

const users = await prisma.user.findMany({ skip: 3, take: 4, });
skip:3 v v v [1][2][3][4][5][6][7][8][9][10] ^ ^ ^ ^ take:4

Implementing pages of results involve skipping the number of pages multiplied by the number of results shown per page.

Sorting and Filtering

Works with sorting and filtering.

const results = await prisma.post.findMany({ skip: 200, take: 20, where: { email: { contains: 'Prisma', }, }, orderBy: { title: 'desc', }, })

Cons of Offset Pagination

It's not efficient for large datasets.

  • When you have a high number of items to skip, DB needs to traverse by the skip number of records, then take the take number of records.
  • e.g. 200K records to skip means DB needs to traverse 200K records, then take 4 records.

Cursor Pagination

Cursor pagination returns a limited range of results starting after a given cursor.

const firstQueryResults = await prisma.post.findMany({ take: 4, where: { title: { contains: 'Prisma' /* Optional filter */, }, }, orderBy: { id: 'asc', }, }) // Bookmark your location in the result set - in this // case, the ID of the last post in the list of 4. const lastPostInResults = firstQueryResults[3] // Remember: zero-based index! :) const myCursor = lastPostInResults.id // Example: 29
AboutContact