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
| Command | Action / Purpose |
|---|---|
npx prisma init | Set up Prisma project with schema.prisma and .env |
npx prisma db push | Push schema state to database without creating migrations |
npx prisma migrate dev --name init | Create and apply SQL migration in development |
npx prisma migrate deploy | Apply pending migrations in production |
npx prisma generate | Regenerate Prisma Client TypeScript types |
npx prisma studio | Launch visual browser IDE to inspect database records |
Common Pitfalls & Tips
[!WARNING] Do not use
prisma db pushin production environments! Useprisma migrate devduring local development andprisma migrate deployin CI/CD deployment scripts.
[!TIP] Use
selectorincludeto control fetched fields, avoiding expensive over-fetching of heavy text or byte columns.