prisma_crud
prisma_crud
ORM
Postgres
Studio
Optimize
Accelerate
Pulse
GuidesExamples
Search
ORM
ORM
Overview
Introduction
Prisma ORM in your stack
Databases
Beyond Prisma ORM
Prisma Schema
Overview
Data model
Introspection
PostgreSQL extensions
Prisma Client
Setup & configuration
Queries
CRUD
Select fields
Relation queries
Filtering and Sorting
Pagination
Aggregation, grouping, and summarizing
Transactions and batch queries
Full-text search
Custom validation
Computed fields
Excluding fields
Custom models
Case sensitivity
Query optimization
Write your own SQL
Fields & types
Extensions
Type safety
Testing
Deployment
Observability & logging
Debugging & troubleshooting
Prisma Migrate
Getting started
Understanding Prisma Migrate
Workflows
Tools
Prisma CLI
Prisma Studio
Reference
Prisma Client API
Prisma Schema
Prisma CLI
Errors
Environment variables
Database features matrix
Supported databases
Connection URLs
System requirements
Preview features
More
Under the hood
Upgrade guides
Comparing Prisma ORM
Development environment Ask AI
Help articles
ORM releases and maturity levels
ORM
Prisma Client
Queries
On this page
CRUD
This page describes how to perform CRUD operations with your generated Prisma Client API. CRUD is an acronym that stands for:
Create
Read
Update
Delete
Refer to the Prisma Client API reference documentation for detailed explanations of each method.
Example schema
All examples are based on the following schema:
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: '[email protected]',
name: 'Elsa Prisma',
},
})
The user's id is auto-generated, and your schema determines which fields are mandatory.
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'
main()
For more information about working with generated types, see: Generated types.
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: '[email protected]' },
{ name: 'Bobo', email: '[email protected]' }, // Duplicate unique key!
{ name: 'Yewande', email: '[email protected]' },
{ name: 'Angelique', email: '[email protected]' },
],
skipDuplicates: true, // Skip 'Bobo'
})
warning
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,DE
COMMIT
SELECT "public"."User"."country", "public"."User"."city", "public"."User"."email", SUM("public"."User"."profileViews"), COUNT(*) FROM "public
Note: Multiple create() statements inside a $transaction results in multiple INSERT statements.
The following video demonstrates how to use createMany() and faker.js to seed a database with sample data:
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.
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: '[email protected]',
},
})
// 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',
},
})
1. Order users by descending ID (largest first) - the largest ID is the most recent
2. 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',
},
})
Prisma Client supports filtering on record fields and related record fields.
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',
},
},
})
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',
},
},
},
],
},
})
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.
The following findUnique() query uses select to return the email and name fields of a specific User record:
const user = await prisma.user.findUnique({
where: {
email: '[email protected]',
},
select: {
email: true,
name: true,
},
})
Select fields
Relation queries
For more information about including relations, see Select fields and include relations.
The following query returns all ADMIN users and includes each user's posts in the result:
const users = await prisma.user.findMany({
where: {
role: 'ADMIN',
},
include: {
posts: true,
},
})
For more information about including relations, see Select fields and include relations.
See Working with relations to find out how to combine include and where for a filtered list of relations - for example, only include a user's published posts.
Update
Update a single record
The following query uses update() to find and update a single User record by email:
const updateUser = await prisma.user.update({
where: {
email: '[email protected]',
},
data: {
name: 'Viola the Magnificent',
},
})
This feature is available in Prisma ORM version 6.2.0 and later for PostgreSQL, CockroachDB, and SQLite.
You can use updateManyAndReturn() in order to update many records and return the resulting objects.
const users = await prisma.user.updateManyAndReturn({
where: {
email: {
contains: 'prisma.io',
}
},
data: {
role: 'ADMIN'
}
})
From version 4.6.0, Prisma Client carries out upserts with database native SQL commands where possible. Learn more.
Prisma Client does not have a findOrCreate() query. You can use upsert() as a workaround. To make upsert() behave like a findOrCreate() method, provide an
empty update parameter to upsert().
warning
A limitation to using upsert() as a workaround for findOrCreate() is that upsert() will only accept unique model fields in the where condition. So it's not possible to
use upsert() to emulate findOrCreate() if the where condition contains non-unique fields.
Update a number field
Use atomic number operations to update a number field based on its current value - for example, increment or multiply. The following query increments the views and
likes fields by 1:
Refer to Working with relations for information about disconnecting (disconnect) and connecting (connect) related records.
Delete
Delete a single record
Attempting to delete a user with one or more posts result in an error, as every Post requires an author - see cascading deletes.
The following query uses deleteMany() to delete all User records where email contains prisma.io:
const deleteUsers = await prisma.user.deleteMany({
where: {
email: {
contains: 'prisma.io',
},
},
})
Attempting to delete a user with one or more posts result in an error, as every Post requires an author - see cascading deletes.
Be aware that this query will fail if the user has any related records (such as posts). In this case, you need to delete the related records first.
warning
In 2.26.0 and later it is possible to do cascading deletes using the preview feature referential actions.
However, the example schema includes a required relation between Post and User, which means that you cannot delete a user with posts:
The change you are trying to make would violate the required relation 'PostToUser' between the `Post` and `User` models.
To resolve this error, you can:
Change the author of the posts to another user before deleting the user.
Delete a user and all their posts with two separate queries in a transaction (all queries must succeed):
const deletePosts = prisma.post.deleteMany({
where: {
authorId: 7,
},
})
The following shows how to delete all records from all tables with Prisma Client and with Prisma Migrate.
When you know the order in which your tables should be deleted, you can use the deleteMany function. This is executed synchronously in a $transaction and can be
used with all types of databases.
✅ Pros:
Works well when you know the structure of your schema ahead of time
Synchronously deletes each tables data
❌ Cons:
When working with relational databases, this function doesn't scale as well as having a more generic solution which looks up and TRUNCATEs your tables regardless
of their relational constraints. Note that this scaling issue does not apply when using the MongoDB connector.
Note: The $transaction performs a cascading delete on each models table so they have to be called in order.
If you are comfortable working with raw SQL, you can perform a TRUNCATE query on a table using $executeRawUnsafe.
In the following examples, the first tab shows how to perform a TRUNCATE on a Postgres database by using a $queryRaw look up that maps over the table and TRUNCATES
all tables in a single query.
The second tab shows performing the same function but with a MySQL database. In this instance the constraints must be removed before the TRUNCATE can be executed,
before being reinstated once finished. The whole process is run as a $transaction
PostgreSQL
MySQL
const tablenames = await prisma.$queryRaw<
Array<{ tablename: string }>
>`SELECT tablename FROM pg_tables WHERE schemaname='public'`
✅ Pros:
Scalable
Very fast
❌ Cons:
Can't undo the operation
Using reserved SQL key words as tables names can cause issues when trying to run a raw query
If you use Prisma Migrate, you can use migrate reset, this will:
A single User
Two new, related Post records
Connect or create Category per post
const u = await prisma.user.create({
include: {
posts: {
include: {
categories: true,
},
},
},
data: {
email: '[email protected]',
posts: {
create: [
{
title: 'My first post',
categories: {
connectOrCreate: [
{
create: { name: 'Introductions' },
where: {
name: 'Introductions',
},
},
{
create: { name: 'Social' },
where: {
name: 'Social',
},
},
],
},
},
{
title: 'How to make cookies',
categories: {
connectOrCreate: [
{
create: { name: 'Social' },
where: {
name: 'Social',
},
},
{
create: { name: 'Cooking' },
where: {
name: 'Cooking',
},
},
],
},
},
],
},
},
})
Edit this page on GitHub
Previous
Queries
Next
Select fields
Example schema
Create
Create a single record
Create a single record using generated types
Create multiple records
Create records and connect or create related records
Create and return multiple records
Read
Get record by ID or unique identifier
Get all records
Get the first record that matches a specific criteria
Get a filtered list of records
Filter by a single field value
Filter by multiple field values
Filter by related record field values
Select a subset of fields
Select a subset of related record fields
Select distinct field values
Include related records
Include a filtered list of relations
Update
Update a single record
Update multiple records
Update and return multiple records
Update or create records
Update a number field
Connect and disconnect related records
Delete
Delete a single record
Delete multiple records
Delete all records
Cascading deletes (deleting related records)
Delete all records from all tables
Deleting all data with deleteMany()
Deleting all data with raw SQL / TRUNCATE
Deleting all records with Prisma Migrate
Advanced query examples
Create a deeply nested tree of records
Prisma logo Prisma logo
Product
ORM
Studio
Optimize
Accelerate
Pulse
Pricing
Changelog
Data Platform status ↗
Resources
Docs
Ecosystem
Playground ↗
ORM Benchmarks ↗
Customer stories
Data guide
Contact us
Community
Support
Enterprise
Partners
OSS Friends
Company
About
Blog
Data DX ↗
Careers
Security & Compliance
Legal
Privacy Policy
Terms of Service
Service Level Agreement
Event Code of Conduct