Overview

This page explains how to get started with Prisma in five minutes. You will learn how to send queries to a SQLite database in a plain TypeScript script using Prisma Client.

This page explains how to get started with Prisma in five minutes. You will learn how to send queries to a SQLite database in a plain Node.js script using Prisma Client.

For demonstration purposes of this guide, you will use a local SQLite database file. This guide does not cover the Prisma setup process.

If you're looking to set up Prisma with your own database, you have these options:

Prerequisites

The only requirement for this guide is to have Node.js (version 10 or higher) installed on your machine.

TypeScript will be added as a local dependency to the project, so no need to install it.

The only requirement for this guide is to have Node.js (version 10 or higher) installed on your machine.

Download SQLite starter project & install dependencies

This guide uses a small starter project that has Prisma configured against a SQLite database file.

Open your terminal and download the starter project with the following command:

Unix (Mac OS, Linux)
Windows
1curl https://codeload.github.com/prisma/prisma-examples/tar.gz/starter | tar -xz --strip=2 prisma-examples-starter/typescript/starter
Unix (Mac OS, Linux)
Windows
1curl https://codeload.github.com/prisma/prisma-examples/tar.gz/starter | tar -xz --strip=2 prisma-examples-starter/javascript/starter

The project is downloaded to directory called starter.


The starter project consists of six files:

  • package.json: Defines your npm dependencies
  • prisma/schema.prisma: Prisma schema file defining your models
  • prisma/.env: Defines your database connection URL as an environment variable
  • prisma/dev.db: A SQLite database file
  • script.ts: A plain, executable TypeScript script
  • tsconfig.json: TypeScript configuration

Note that the dependencies defined in your project are:

  • @prisma/cli: The Prisma CLI which you can invoke with npx prisma
  • @prisma/client: Prisma Client library for accessing your database
  • typescript: TypeScript toolchain
  • ts-node: Used to execute the TypeScript script

The starter project consists of five files:

  • package.json: Defines your npm dependencies
  • prisma/schema.prisma: Prisma schema file defining your models
  • prisma/.env: Defines your database connection URL as an environment variable
  • prisma/dev.db: A SQLite database file
  • script.js: A plain, executable Node.js script

Note that the only two dependencies defined in your project are:

  • @prisma/cli: The Prisma CLI which you can invoke with npx prisma
  • @prisma/client: Prisma Client library for accessing your database

The SQLite database file prisma/dev.db contains two tables with dummy data:

User

idemailname
1"sarah@prisma.io""Sarah"
2"maria@prisma.io""Maria"

Post

idtitlecontentpublishedauthorId
1"Hello World"nullfalse2

Note: The authorId column references the id column of the User table: the 2 in the authorId column refers to the User record with an id value of 2.

Before you move on, navigate into the starter directory and install the npm dependencies with these commands:

1cd starter
2npm install

Write your first query with Prisma Client

In this section, you will write your first query with Prisma Client. For reference, this is what the Prisma schema looks like that your Prisma Client was generated from:

1datasource db {
2 provider = "sqlite"
3 url = env("DATABASE_URL")
4}
5
6generator client {
7 provider = "prisma-client-js"
8}
9
10model Post {
11 id Int @id @default(autoincrement())
12 title String
13 content String?
14 published Boolean @default(false)
15 author User? @relation(fields: [authorId], references: [id])
16 authorId Int?
17}
18
19model User {
20 id Int @id @default(autoincrement())
21 email String @unique
22 name String?
23 posts Post[]
24}

The code inside script.ts currently looks as follows:

1import { PrismaClient } from "@prisma/client"
2
3const prisma = new PrismaClient()
4
5// A `main` function so that you can use async/await
6async function main() {
7 // ... you will write your Prisma Client queries here
8}
9
10main()
11 .catch(e => {
12 throw e
13 })
14 .finally(async () => {
15 await prisma.disconnect()
16 })

The code inside script.js currently looks as follows:

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 .catch(e => {
11 throw e
12 })
13 .finally(async () => {
14 await prisma.disconnect()
15 })

Here's a quick overview of the main parts:

  1. Import PrismaClient constructor from the @prisma/client node module
  2. Instantiate PrismaClient
  3. Define an async function called 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:

1async function main() {
2 const allUsers = await prisma.user.findMany()
3 console.log(allUsers)
4}

Now run the code with this command:

1npm run dev

This should print the following result to your terminal output:

1[
2 { id: 1, email: "sarah@prisma.io", name: "Sarah" },
3 { id: 2, email: "maria@prisma.io", name: "Maria" },
4]

One of the main features of Prisma Client is the ease of working with relations. You can retrieve the posts of each user by using the include option. Adjust your code to look as follows:

1async function main() {
2 const allUsers = await prisma.user.findMany({
3 include: { posts: true },
4 })
5 // use `console.dir` to print nested objects
6 console.dir(allUsers, { depth: null })
7}

Run the code again with:

1npm run dev

Each object inside allUsers now includes a posts field that represents data retrieved by following the relation between the User and Post tables:

1[
2 { id: 1, email: 'sarah@prisma.io', name: 'Sarah', posts: [] },
3 {
4 id: 2,
5 email: 'maria@prisma.io',
6 name: 'Maria',
7 posts: [
8 {
9 id: 1,
10 title: 'Hello World',
11 content: null,
12 published: false,
13 authorId: 2
14 }
15 ]
16 }
17]

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:

1const allUsers: (User & {
2 posts: Post[];
3})[]
4
5export type Post = {
6 id: number
7 title: string
8 content: string | null
9 published: boolean
10 authorId: number | null
11}

Congratulations, you just wrote your first query with Prisma Client 🎉

Write data into the database

The findMany query you used in the previous section only reads data from the database. 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:

1async function main() {
2 const post = await prisma.post.create({
3 data: {
4 title: "Prisma makes databases easy",
5 author: {
6 connect: { email: "sarah@prisma.io" },
7 },
8 },
9 })
10 console.log(post)
11
12 const allUsers = await prisma.user.findMany({
13 include: { posts: true },
14 })
15 console.dir(allUsers, { depth: null })
16}

This code creates a new Post record and connects it in a nested write to an existing User record.

Run the code with this command:

1npm run dev

The output should look similar to this:

1{
2 id: 2,
3 title: 'Prisma makes databases easy',
4 content: null,
5 published: false,
6 authorId: 1
7}
8[
9 {
10 id: 1,
11 email: 'sarah@prisma.io',
12 name: 'Sarah',
13 posts: [
14 {
15 id: 2,
16 title: 'Prisma makes databases easy',
17 content: null,
18 published: false,
19 authorId: 1
20 }
21 ]
22 },
23 {
24 id: 2,
25 email: 'maria@prisma.io',
26 name: 'Maria',
27 posts: [
28 {
29 id: 1,
30 title: 'Hello World',
31 content: null,
32 published: false,
33 authorId: 2
34 }
35 ]
36 }
37]

The query added a new record to the Post table:

Post

idtitlecontentpublishedauthorId
1"Hello World"nullfalse2
2"Prisma makes databases easy"nullfalse1

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:

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

Now run the code using the same command as before:

1npm run dev

You will see the following output:

1{
2 id: 2,
3 title: 'Prisma makes databases easy',
4 content: null,
5 published: true,
6 authorId: 1
7}

The Post record with an id of 2 has been updated in the database:

Post

idtitlecontentpublishedauthorId
1"Hello World"nullfalse2
2"Prisma makes databases easy"nulltrue1

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

Next steps

This section lists a number of potential next steps you can now take from here. Feel free to explore these or read the Introduction page to get a high-level overview of Prisma.

Continue exploring the Prisma Client API

You can send a variety of queries with the Prisma Client API. Check out the API reference and use your existing SQLite-based setup from this guide to try them out.

Tip: You can use your editor's auto-completion feature to learn about the different API calls and the arguments it takes. Auto-completion is commonly invoked by hitting CTRL+SPACE on your keyboard.

Here are a few suggestions for a number of more queries you can send with Prisma Client:

Filter all Post records that contain "prisma"

1const filteredPosts = await prisma.post.findMany({
2 where: {
3 OR: [
4 { title: { contains: "prisma" } },
5 { content: { contains: "prisma" } },
6 ],
7 },
8})

Create a new User and a new Post record in the same query

1const user = await prisma.user.create({
2 data: {
3 name: "Nancy",
4 email: "nancy@prisma.io",
5 posts: {
6 create: { title: "Join us for Prisma Day 2020" },
7 },
8 },
9})

Use the fluent relations API to retrieve the Post records of a User

1const posts = await prisma.user
2 .findOne({
3 where: { email: "sarah@prisma.io" },
4 })
5 .posts()

Delete a User record

1const deletedUser = await prisma.user.delete({
2 where: { email: "sarah@prisma.io" },
3})

Set up Prisma with your own database

To learn how to connect Prisma to your own database, you can follow the respective setup guide.

Set up a new project from scratch

The following guides both explain how you can set up a new project from scratch using your own database as well as how to send queries with Prisma Client. The first one uses SQL migrations and introspection while the second one uses Prisma Migrate as the main Prisma workflow.

SQL migrationsPrisma Migrate

Add Prisma to an existing npm project

When adding Prisma to an already existing npm project, you can obtain your initial data model through introspection.

Add Prisma to existing project

Explore the data in Prisma Studio (experimental)

Prisma Studio is a visual editor for the data in your database. You can run it with the following command:

1npx prisma studio --experimental

Change the database schema (e.g. create more tables)

Changing your database schema using SQL typically happens with the following steps.

First, create a new table in your database, e.g. with this command in your terminal:

Unix (Mac OS, Linux)
Windows
1sqlite3 ./prisma/dev.db \
2'CREATE TABLE "Profile" (
3 "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
4 "bio" TEXT,
5 "userId" INTEGER NOT NULL UNIQUE REFERENCES "User"(id) ON DELETE SET NULL
6)'

Then, introspect your database with this command from the Prisma CLI:

1npx prisma introspect

This updates your Prisma schema in prisma/schema.prisma.

Note that after the introspection, you might want to configure your Prisma Client API.

Changing your database schema using Prisma Migrate typically happens with the following steps.

First, adjust the data model in your Prisma schema, e.g. by adding a new model:

1model Profile {
2 id Int @id @default(autoincrement())
3 bio String
4 user User @relation(fields: [userId], references: [id])
5 userId Int
6}
7
8model User {
9 id Int @id @default(autoincrement())
10 email String @unique
11 name String?
12 posts Post[]
13 profile Profile?
14}
15
16model Post {
17 id Int @id @default(autoincrement())
18 title String
19 content String?
20 published Boolean @default(false)
21 author User? @relation(fields: [authorId], references: [id])
22 authorId Int?
23}

Next, create a new migration by running the following command:

1npx prisma migrate save --name "add-profile" --experimental
2npx prisma migrate up --experimental

Now you can run the migration against the database npx prisma migrate up --experimental.

Finally, re-generate Prisma Client with this command:

1npx prisma generate

This updates the generated Prisma Client library in node_modules/@prisma/client.

You can now run queries against the new Profile table, e.g. using prisma.profile.findMany().

Try a Prisma example

The prisma-examples repository contains a number of ready-to-run examples:

TypeScript

DemoStackDescription
rest-nextjsFullstackSimple Next.js app (React) with a REST API
graphql-nextjsFullstackSimple Next.js app (React) with a GraphQL API
graphql-apollo-serverBackend onlySimple GraphQL server based on apollo-server
rest-expressBackend onlySimple REST API with Express.JS
grpcBackend onlySimple gRPC API

JavaScript (Node.js)

DemoStackDescription
rest-nextjsFullstackSimple Next.js app (React) with a REST API
graphql-apollo-serverBackend onlySimple GraphQL server based on apollo-server
rest-expressBackend onlySimple REST API with Express.JS
grpcBackend onlySimple gRPC API
Edit this page on Github