Querying the database

JavaScript
SQL Server

Write your first query with Prisma Client

Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client.

Create a new file named index.ts and add the following code to it:

index.ts
1import { PrismaClient } from '@prisma/client'
2
3const prisma = new PrismaClient()
4
5async function main() {
6 // ... you will write your Prisma Client queries here
7}
8
9main()
10 .then(async () => {
11 await prisma.$disconnect()
12 })
13 .catch(async (e) => {
14 console.error(e)
15 await prisma.$disconnect()
16 process.exit(1)
17 })

Create a new file named index.js and add the following code to it:

index.js
1const { PrismaClient } = require('@prisma/client')
2
3const prisma = new PrismaClient()
4
5async function main() {
6 // ... you will write your Prisma Client queries here
7}
8
9main()
10 .then(async () => {
11 await prisma.$disconnect()
12 })
13 .catch(async (e) => {
14 console.error(e)
15 await prisma.$disconnect()
16 process.exit(1)
17 })

Here's a quick overview of the different parts of the code snippet:

  1. Import the PrismaClient constructor from the @prisma/client node module
  2. Instantiate PrismaClient
  3. Define an async function named main to send queries to the database
  4. Call the main function
  5. Close the database connections when the script terminates

Inside the main function, add the following query to read all User records from the database and print the result:

index.ts
1async function main() {
2 // ... you will write your Prisma Client queries here
+ const allUsers = await prisma.user.findMany()
+ console.log(allUsers)
5}
index.js
1async function main() {
- // ... you will write your Prisma Client queries here
+ const allUsers = await prisma.user.findMany()
+ console.log(allUsers)
5}

Now run the code with this command:

$npx ts-node index.ts
$node index.js

This should print an empty array because there are no User records in the database yet:

[]

Write data into the database

The findMany query you used in the previous section only reads data from the database (although it was still empty). In this section, you'll learn how to write a query to write new records into the Post and User tables.

Adjust the main function to send a create query to the database:

index.ts
1async function main() {
+ await prisma.user.create({
+ data: {
+ name: 'Alice',
+ email: 'alice@prisma.io',
+ posts: {
+ create: { title: 'Hello World' },
+ },
+ profile: {
+ create: { bio: 'I like turtles' },
+ },
+ },
+ })
+
+ const allUsers = await prisma.user.findMany({
+ include: {
+ posts: true,
+ profile: true,
+ },
+ })
+ console.dir(allUsers, { depth: null })
22}
index.js
1async function main() {
+ await prisma.user.create({
+ data: {
+ name: 'Alice',
+ email: 'alice@prisma.io',
+ posts: {
+ create: { title: 'Hello World' },
+ },
+ profile: {
+ create: { bio: 'I like turtles' },
+ },
+ },
+ })
+
+ const allUsers = await prisma.user.findMany({
+ include: {
+ posts: true,
+ profile: true,
+ },
+ })
+ console.dir(allUsers, { depth: null })
22}

This code creates a new User record together with new Post and Profile records using a nested write query. The User record is connected to the two other ones via the Post.author ↔ User.posts and Profile.user ↔ User.profile relation fields respectively.

Notice that you're passing the include option to findMany which tells Prisma Client to include the posts and profile relations on the returned User objects.

Run the code with this command:

$npx ts-node index.ts
$node index.js

The output should look similar to this:

[
{
email: 'alice@prisma.io',
id: 1,
name: 'Alice',
posts: [
{
content: null,
createdAt: 2020-03-21T16:45:01.246Z,
updatedAt: 2020-03-21T16:45:01.246Z,
id: 1,
published: false,
title: 'Hello World',
authorId: 1,
}
],
profile: {
bio: 'I like turtles',
id: 1,
userId: 1,
}
}
]

Also note that allUsers is statically typed thanks to Prisma Client's generated types. You can observe the type by hovering over the allUsers variable in your editor. It should be typed as follows:

const allUsers: (User & {
posts: Post[]
})[]
export type Post = {
id: number
title: string
content: string | null
published: boolean
authorId: number | null
}

The query added new records to the User and the Post tables:

User

idemailname
1"alice@prisma.io""Alice"

Post

idcreatedAtupdatedAttitlecontentpublishedauthorId
12020-03-21T16:45:01.246Z2020-03-21T16:45:01.246Z"Hello World"nullfalse1

Profile

idbiouserId
1"I like turtles"1

Note: The numbers in the authorId column on Post and userId column on Profile both reference the id column of the User table, meaning the id value 1 column therefore refers to the first (and only) User record in the database.

Before moving on to the next section, you'll "publish" the Post record you just created using an update query. Adjust the main function as follows:

index.ts
1async function main() {
2 const post = await prisma.post.update({
3 where: { id: 1 },
4 data: { published: true },
5 })
6 console.log(post)
7}
index.js
1async function main() {
2 const post = await prisma.post.update({
3 where: { id: 1 },
4 data: { published: true },
5 })
6 console.log(post)
7}

Now run the code using the same command as before:

$npx ts-node index.ts

Now run the code using the same command as before:

$node index.js

You will see the following output:

{
id: 1,
title: 'Hello World',
content: null,
published: true,
authorId: 1
}

The Post record with an id of 1 now got updated in the database:

Post

idtitlecontentpublishedauthorId
1"Hello World"nulltrue1

Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀