Logo

dev-resources.site

for different kinds of informations.

Pagination and Sorting with Prisma in TypeScript

Published at
10/26/2024
Categories
prisma
Author
md_enayeturrahman_2560e3
Categories
1 categories in total
prisma
open
Author
24 person written this
md_enayeturrahman_2560e3
open
Pagination and Sorting with Prisma in TypeScript

In this guide, we’ll explore two main types of pagination techniques, offset pagination and cursor pagination, using Prisma. We’ll also cover how to sort data using Prisma’s orderBy feature.

  1. Offset Pagination

Offset pagination is a straightforward technique where you specify the number of records to skip and the number to take. This is useful when you want to retrieve a subset of records without worrying about specific starting points.

Create a file named offset.ts:

offset.ts

import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

const main = async () => {
  // Offset pagination
  const offsetData = await prisma.post.findMany({
    skip: 5, // Skip the first 5 records
    take: 2, // Take the next 2 records
  });

  console.log("Offset Pagination Result:", offsetData);
};

main();

Enter fullscreen mode Exit fullscreen mode

In this example:

skip: 5 skips the first five records.
take: 2 retrieves the next two records after skipping.
Limitation: For large datasets, offset pagination can slow down since the database has to process all records up to the offset point before retrieving the specified records.

  1. Cursor-Based Pagination

Cursor-based pagination is more efficient for large datasets. Instead of skipping a specific number of records, it starts from a known record (defined by a unique cursor) and retrieves the next set of records.

Create a file named cursor.ts:

cursor.ts

import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

const main = async () => {
  // Cursor-based pagination
  const cursorData = await prisma.post.findMany({
    cursor: {
      id: 15, // Start from the record with id 15
    },
    skip: 5, // Skip 5 records after the starting point
    take: 2, // Take the next 2 records
  });

  console.log("Cursor Pagination Result:", cursorData);
};

main();

Enter fullscreen mode Exit fullscreen mode

In this example:

cursor: { id: 15 } specifies that the pagination should start from the record with id: 15.
skip: 5 skips the next five records after the starting point.
take: 2 retrieves the following two records.
Difference Between Offset and Cursor Pagination
Offset: Skips a specified number of records from the beginning.
Cursor: Starts from a specific record (the cursor) and skips a certain number of records from there.

  1. Sorting with orderBy

Prisma’s orderBy feature allows you to sort results in ascending or descending order. You can apply sorting to fields like id, title, content, published, authorName, createdAt, or updatedAt.

Create a file named sort.ts:

sort.ts

import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

const main = async () => {
  // Sorting data in ascending order by title
  const sortData = await prisma.post.findMany({
    orderBy: {
      title: 'asc', // Sort by title in ascending order
    },
  });

  console.log("Sorted Data:", sortData);
};

main();

Enter fullscreen mode Exit fullscreen mode

In this example, title: 'asc' sorts the records by the title field in ascending order. Change 'asc' to 'desc' for descending order.

Sorting with Conditions

You can combine sorting with conditional filters to retrieve only specific records, as shown below.

import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

const main = async () => {
  const sortData = await prisma.post.findMany({
    orderBy: {
      id: 'asc', // Sort by id in ascending order
    },
    where: {
      title: 'Title 1', // Filter to records where title is 'Title 1'
    },
  });

  console.log("Conditionally Sorted Data:", sortData);
};

main();

Enter fullscreen mode Exit fullscreen mode

This code will retrieve all posts with title equal to 'Title 1' and sort them by id in ascending order.

  1. Combining Pagination and Sorting

You can combine pagination and sorting for more refined queries. Here’s an example where we apply both sorting and offset pagination.

offset_sort_pagination.ts

import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

const main = async () => {
  const sortAndPaginateData = await prisma.post.findMany({
    orderBy: {
      id: 'asc', // Sort by id in ascending order
    },
    skip: 3, // Skip the first 3 records
    take: 2, // Take the next 2 records
    where: {
      title: 'Title 1', // Filter to records where title is 'Title 1'
    },
  });

  console.log("Sorted and Paginated Data:", sortAndPaginateData);
};

main();

Enter fullscreen mode Exit fullscreen mode

This query retrieves records where the title is 'Title 1', sorts them by id in ascending order, skips the first three records, and takes the next two.

These examples demonstrate how to implement pagination (offset and cursor-based) and sorting using Prisma. Combining these techniques enables more efficient data retrieval, especially when working with large datasets.

prisma Article's
30 articles in total
Favicon
How to Fix the “Record to Delete Does Not Exist” Error in Prisma
Favicon
Building Type-Safe APIs: Integrating NestJS with Prisma and TypeScript
Favicon
Deploying an Existing Express API + Prisma + Supabase Project to Vercel
Favicon
Exploring the Power of Full-Stack Development with Next.js and Prisma
Favicon
How to integrate GitHub CopilotKit with Prisma Integration into your nextJs project Using OpenAI
Favicon
วิธีทำ Auth API ด้วย Express, JWT, MySQL และ Prisma
Favicon
Prisma
Favicon
How we built "Space-Ease" using Next.js
Favicon
Query Objects Instead of Repositories: A Modern Approach to Data Access
Favicon
Common Data Loss Scenarios & Solutions in Prisma Schema Changes
Favicon
How I Solved Common Prisma ORM Errors: Debugging Tips and Best Practices
Favicon
Prisma 101 baby.
Favicon
Prisma
Favicon
QueryBuilder in Action Part 1
Favicon
Prisma ORM: Revolutionizing Database Interactions
Favicon
Prisma & MongoDB: server to be run as a replica set
Favicon
Using GenAI to Tackle Complex Prisma Model Migrations
Favicon
When Embedded AuthN Meets Embedded AuthZ - Building Multi-Tenant Apps With Better-Auth and ZenStack
Favicon
Building Multi-Tenant Apps Using StackAuth's "Teams" and Next.js
Favicon
The Most Awaited Prisma Course Is Here! 😍
Favicon
**Building a Full-Stack Next.js Starter Kit: Authentication, GraphQL, and Testing**
Favicon
Integrate DAYTONA and let the magic begin....
Favicon
Cloudflare D1 and Prisma: Not a Good Combination (For Now)
Favicon
Resolving the `DO $$` Issue in Drizzle ORM with Nile Postgres
Favicon
Nuxt Authorization: How to Implement Team Role-Based Access Control in Nuxt 3
Favicon
Getting Started with Prisma, SQLite, and Express
Favicon
Senior Developer Advocate
Favicon
Building Multi-Tenant Apps Using Clerk's "Organization" and Next.js
Favicon
How to use ORMs (Prisma / Drizzle / Knex.js) in a TypeScript backend built with Encore.ts
Favicon
Pagination and Sorting with Prisma in TypeScript

Featured ones: