Skip to content
>_devvkit
$devvkit learn --librarie prisma-guide

Prisma Guide

[orm][database][typescript]
JavaScript / TypeScript
Install
npm install prisma @prisma/client
npx prisma init

Prisma replaces traditional ORMs with a type-safe query API. Define schema in Prisma Schema Language.

Run prisma generate to get a fully typed client. Queries are validated at compile time.

Supports PostgreSQL, MySQL, SQLite, SQL Server, MongoDB, and CockroachDB.

Setup

InitCreate prisma directory.
npx prisma init
StudioVisual database browser.
npx prisma studio

Schema Design

SchemaDefine a User model.
model User {
  id        String   @id @default(cuid())
  email     String   @unique
  name      String?
  posts     Post[]
  createdAt DateTime @default(now())
}
Related modelDefine Post with relation.
model Post {
  id       String @id @default(cuid())
  title    String
  author   User   @relation(fields: [authorId], references: [id])
  authorId String
}

CRUD

Create recordInsert data.
const user = await prisma.user.create({
  data: { email: 'alice@example.com', name: 'Alice' },
});
Find uniqueGet by unique column.
const user = await prisma.user.findUnique({
  where: { email: 'alice@example.com' },
});
Find with filtersQuery with conditions.
const users = await prisma.user.findMany({
  where: { name: { contains: 'Ali' } },
  orderBy: { createdAt: 'desc' },
  take: 10,
});
UpdateModify existing data.
await prisma.user.update({
  where: { id: 'abc123' },
  data: { name: 'Alice Updated' },
});
DeleteRemove a record.
await prisma.user.delete({ where: { id: 'abc123' } });

Relations

Include relationsEager load related.
const user = await prisma.user.findUnique({
  where: { id: 'abc123' },
  include: { posts: true },
});
TransactionAtomic operations.
const [user, post] = await prisma.([
  prisma.user.create({ data: { email: 'x@x.com' } }),
  prisma.post.create({ data: { title: 'X', authorId: '...' } }),
]);

Migrations

MigrateCreate and apply migration.
npx prisma migrate dev --name add_users