CRUD
This page describes how to perform CRUD operations with your generated Prisma Client API. CRUD is an acronym that stands for:
Refer to the Prisma Client API reference documentation for detailed explanations of each method.
Example schema
All examples are based on the following schema:
Expand for sample schema
- Relational databases
- MongoDB
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model ExtendedProfile {
id Int @id @default(autoincrement())
biography String
user User @relation(fields: [userId], references: [id])
userId Int @unique
}
model User {
id Int @id @default(autoincrement())
name String?
email String @unique
profileViews Int @default(0)
role Role @default(USER)
coinflips Boolean[]
posts Post[]
profile ExtendedProfile?
}
model Post {
id Int @id @default(autoincrement())
title String
published Boolean @default(true)
author User @relation(fields: [authorId], references: [id])
authorId Int
comments Json?
views Int @default(0)
likes Int @default(0)
categories Category[]
}
model Category {
id Int @id @default(autoincrement())
name String @unique
posts Post[]
}
enum Role {
USER
ADMIN
}
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model ExtendedProfile {
id String @id @default(auto()) @map("_id") @db.ObjectId
biography String
user User @relation(fields: [userId], references: [id])
userId String @unique @db.ObjectId
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String?
email String @unique
profileViews Int @default(0)
role Role @default(USER)
coinflips Boolean[]
posts Post[]
profile ExtendedProfile?
}
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
title String
published Boolean @default(true)
author User @relation(fields: [authorId], references: [id])
authorId String @db.ObjectId
comments Json?
views Int @default(0)
likes Int @default(0)
categories Category[]
}
model Category {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String @unique
posts Post[]
}
enum Role {
USER
ADMIN
}
For relational databases, use db push
command to push the example schema to your own database
npx prisma db push
For MongoDB, ensure your data is in a uniform shape and matches the model defined in the Prisma schema.
Create
Create a single record
The following query creates (create()
) a single user with two fields:
const user = await prisma.user.create({
data: {
email: 'elsa@prisma.io',
name: 'Elsa Prisma',
},
})
The user's id
is auto-generated, and your schema determines which fields are mandatory.
Create a single record using generated types
The following example produces an identical result, but creates a UserCreateInput
variable named user
outside the context of the create()
query. After completing a simple check ("Should posts be included in this create()
query?"), the user
variable is passed into the query:
import { PrismaClient, Prisma } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
let includePosts: boolean = false
let user: Prisma.UserCreateInput
// Check if posts should be included in the query
if (includePosts) {
user = {
email: 'elsa@prisma.io',
name: 'Elsa Prisma',
posts: {
create: {
title: 'Include this post!',
},
},
}
} else {
user = {
email: 'elsa@prisma.io',
name: 'Elsa Prisma',
}
}
// Pass 'user' object into query
const createUser = await prisma.user.create({ data: user })
}
main()
For more information about working with generated types, see: Generated types.
Create multiple records
Prisma Client supports bulk inserts as a GA feature in 2.20.0 and later.
The following createMany()
query creates multiple users and skips any duplicates (email
must be unique):
const createMany = await prisma.user.createMany({
data: [
{ name: 'Bob', email: 'bob@prisma.io' },
{ name: 'Bobo', email: 'bob@prisma.io' }, // Duplicate unique key!
{ name: 'Yewande', email: 'yewande@prisma.io' },
{ name: 'Angelique', email: 'angelique@prisma.io' },
],
skipDuplicates: true, // Skip 'Bobo'
})
{
count: 3
}
Note skipDuplicates
is not supported when using MongoDB, SQLServer, or SQLite.
createMany()
uses a single INSERT INTO
statement with multiple values, which is generally more efficient than a separate INSERT
per row:
BEGIN
INSERT INTO "public"."User" ("id","name","email","profileViews","role","coinflips","testing","city","country") VALUES (DEFAULT,$1,$2,$3,$4,DEFAULT,DEFAULT,DEFAULT,$5), (DEFAULT,$6,$7,$8,$9,DEFAULT,DEFAULT,DEFAULT,$10), (DEFAULT,$11,$12,$13,$14,DEFAULT,DEFAULT,DEFAULT,$15), (DEFAULT,$16,$17,$18,$19,DEFAULT,DEFAULT,DEFAULT,$20) ON CONFLICT DO NOTHING
COMMIT
SELECT "public"."User"."country", "public"."User"."city", "public"."User"."email", SUM("public"."User"."profileViews"), COUNT(*) FROM "public"."User" WHERE 1=1 GROUP BY "public"."User"."country", "public"."User"."city", "public"."User"."email" HAVING AVG("public"."User"."profileViews") >= $1 ORDER BY "public"."User"."country" ASC OFFSET $2
Note: Multiple
create()
statements inside a$transaction
results in multipleINSERT
statements.
The following video demonstrates how to use createMany()
and faker.js to seed a database with sample data:
Create records and connect or create related records
See Working with relations > Nested writes for information about creating a record and one or more related records at the same time.
Create and return multiple records
This feature is available in Prisma ORM version 5.14.0 and later for PostgreSQL, CockroachDB and SQLite.
You can use createManyAndReturn()
in order to create many records and return the resulting objects.
const users = await prisma.user.createManyAndReturn({
data: [
{ name: 'Alice', email: 'alice@prisma.io' },
{ name: 'Bob', email: 'bob@prisma.io' },
],
})
relationLoadStrategy: join
is not available when using createManyAndReturn()
.
Read
Get record by ID or unique identifier
The following queries return a single record (findUnique()
) by unique identifier or ID:
// By unique identifier
const user = await prisma.user.findUnique({
where: {
email: 'elsa@prisma.io',
},
})
// By ID
const user = await prisma.user.findUnique({
where: {
id: 99,
},
})
If you are using the MongoDB connector and your underlying ID type is ObjectId
, you can use the string representation of that ObjectId
:
// By ID
const user = await prisma.user.findUnique({
where: {
id: '60d5922d00581b8f0062e3a8',
},
})
Get all records
The following findMany()
query returns all User
records:
const users = await prisma.user.findMany()
You can also paginate your results.
Get the first record that matches a specific criteria
The following findFirst()
query returns the most recently created user with at least one post that has more than 100 likes:
- Order users by descending ID (largest first) - the largest ID is the most recent
- Return the first user in descending order with at least one post that has more than 100 likes
const findUser = await prisma.user.findFirst({
where: {
posts: {
some: {
likes: {
gt: 100,
},
},
},
},
orderBy: {
id: 'desc',
},
})
Get a filtered list of records
Prisma Client supports filtering on record fields and related record fields.
Filter by a single field value
The following query returns all User
records with an email that ends in "prisma.io"
:
const users = await prisma.user.findMany({
where: {
email: {
endsWith: 'prisma.io',
},
},
})
Filter by multiple field values
The following query uses a combination of operators to return users whose name start with E
or administrators with at least 1 profile view:
const users = await prisma.user.findMany({
where: {
OR: [
{
name: {
startsWith: 'E',
},
},
{
AND: {
profileViews: {
gt: 0,
},
role: {
equals: 'ADMIN',
},
},
},
],
},
})
Filter by related record field values
The following query returns users with an email that ends with prisma.io
and have at least one post (some
) that is not published:
const users = await prisma.user.findMany({
where: {
email: {
endsWith: 'prisma.io',
},
posts: {
some: {
published: false,
},
},
},
})
See Working with relations for more examples of filtering on related field values.