Prisma ORM Syntax Cheat Sheet

Quick reference guide for Prisma ORM: Schema definition, relations, client queries, and CLI migrations.

Databases
prisma
orm
typescript

Prisma is a next-generation Node.js and TypeScript ORM that uses a declarative schema modeling language to generate type-safe database queries.

`schema.prisma` Models & Relations

prisma
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id        Int      @id @default(autoincrement())
  email     String   @unique
  name      String?
  posts     Post[]
  createdAt DateTime @default(now())

  @@map("users")
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  authorId  Int
  author    User     @relation(fields: [authorId], references: [id], onDelete: Cascade)

  @@index([authorId])
  @@map("posts")
}

Prisma Client CRUD Queries

typescript
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

// Create record with nested relation
const newUser = await prisma.user.create({
  data: {
    email: "user@example.com",
    name: "Alice",
    posts: {
      create: [{ title: "First Post" }, { title: "Second Post" }]
    }
  },
  include: { posts: true }
});

// Read with filtering and pagination
const users = await prisma.user.findMany({
  where: {
    email: { endsWith: "@example.com" }
  },
  take: 10,
  skip: 0,
  orderBy: { createdAt: "desc" }
});

// Upsert (update or insert)
const user = await prisma.user.upsert({
  where: { email: "user@example.com" },
  update: { name: "Alice Smith" },
  create: { email: "user@example.com", name: "Alice Smith" }
});

Essential Prisma CLI Commands

Table
CommandAction / Purpose
npx prisma initSet up Prisma project with schema.prisma and .env
npx prisma db pushPush schema state to database without creating migrations
npx prisma migrate dev --name initCreate and apply SQL migration in development
npx prisma migrate deployApply pending migrations in production
npx prisma generateRegenerate Prisma Client TypeScript types
npx prisma studioLaunch visual browser IDE to inspect database records

Common Pitfalls & Tips

[!WARNING] Do not use prisma db push in production environments! Use prisma migrate dev during local development and prisma migrate deploy in CI/CD deployment scripts.

[!TIP] Use select or include to control fetched fields, avoiding expensive over-fetching of heavy text or byte columns.