Prisma Cheatsheet
Prisma is a modern ORM that provides type-safe database access with automatic migrations and a powerful query API.
Prisma is a next-generation ORM that provides type-safe database access, automatic migrations, and a powerful query API. It eliminates SQL boilerplate while maintaining type safety and performance.
NOTE: Tested using the latest version at time of writing, v5.x
Schema Definition
Define your database schema in schema.prisma.
// schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
createdAt DateTime @default(now())
}
Basic Queries
Query data with type-safe methods.
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
// Find all
const users = await prisma.user.findMany();
// Find one
const user = await prisma.user.findUnique({
where: { id: 1 }
});
Creating Records
Create new records.
// Create
const user = await prisma.user.create({
data: {
email: 'user@example.com',
name: 'John Doe'
}
});
Updating Records
Update existing records.
// Update
const user = await prisma.user.update({
where: { id: 1 },
data: { name: 'Jane Doe' }
});
// Upsert (update or create)
const user = await prisma.user.upsert({
where: { email: 'user@example.com' },
update: { name: 'Updated' },
create: { email: 'user@example.com', name: 'New User' }
});
Relations
Query related data.
// Include relations
const user = await prisma.user.findUnique({
where: { id: 1 },
include: { posts: true }
});
Transactions
Execute multiple operations atomically.
const result = await prisma.$transaction(async (tx) => {
const user = await tx.user.create({ data: { email: 'user@example.com' } });
const post = await tx.post.create({
data: {
title: 'My Post',
authorId: user.id
}
});
return { user, post };
});
Migrations
Manage database schema changes.
# Create migration
npx prisma migrate dev --name add_user_table
# Apply migrations
npx prisma migrate deploy
# Generate Prisma Client
npx prisma generate
Prisma simplifies database access with type safety and powerful queries. Start with the schema, then explore relations and transactions.
For full documentation, see https://www.prisma.io/docs