rembrembdocs

Defines a data source in the Prisma schema.

Fields

A datasource block accepts the following fields:

NameRequiredTypeDescription
providerYesString (postgresql, mysql, sqlite, sqlserver, mongodb, cockroachdb)Specifies the database connector to use.
relationModeNoString (foreignKeys, prisma)Sets whether referential integrity is enforced by foreign keys or by Prisma.
schemasNoArray of stringsList of database schemas to include (multi-schema support, PostgreSQL and SQL Server).
extensionsNoArray of extension namesPostgreSQL extensions to enable.

Connection URLs (url, directUrl, shadowDatabaseUrl) are configured in prisma.config.ts, not in the schema file.

The following providers are available:

Examples

PostgreSQL datasource

datasource db {
  provider = "postgresql"
}

Configure the connection URL in prisma.config.ts:

import { defineConfig, env } from "prisma/config";

export default defineConfig({
  datasource: {
    url: env("DATABASE_URL"),
  },
});

Learn more about PostgreSQL connection strings here.

Specify a PostgreSQL data source via an environment variable

In this example, the target database is available with the following credentials:

datasource db {
  provider = "postgresql"
}

When running a Prisma CLI command that needs the database connection URL (e.g. prisma generate), you need to make sure that the DATABASE_URL environment variable is set.

One way to do so is by creating a .env file with the following contents. Note that the file must be in the same directory as your schema.prisma file to automatically picked up the Prisma CLI.

DATABASE_URL=postgresql://johndoe:mypassword@localhost:5432/mydb?schema=public

MySQL datasource

datasource db {
  provider = "mysql"
}

Learn more about MySQL connection URLs.

MongoDB datasource

datasource db {
  provider = "mongodb"
}

Learn more about MongoDB connection URLs.

SQLite datasource

datasource db {
  provider = "sqlite"
}

Learn more about SQLite connection URLs.

CockroachDB datasource

datasource db {
  provider = "cockroachdb"
}

CockroachDB uses the same connection URL format as PostgreSQL. Learn more about PostgreSQL connection URLs.

Multi-schema datasource (PostgreSQL)

datasource db {
  provider = "postgresql"
  schemas  = ["public", "analytics"]
}

Defines a generator in the Prisma schema.

Fields for prisma-client-js provider

This is the default generator for Prisma ORM 6.x and earlier versions. Learn more about generators.

A generator block accepts the following fields:

NameRequiredTypeDescription
providerYesprisma-client-jsDescribes which generator to use. This can point to a file that implements a generator or specify a built-in generator directly.
outputNoString (file path)Determines the location for the generated client, learn more. Default: node_modules/.prisma/client
previewFeaturesNoList of EnumsUse intellisense to see list of currently available Preview features (Ctrl+Space in Visual Studio Code) Default: none
engineTypeNoEnum (library or binary)Defines the query engine type to download and use. Default: library
binaryTargetsNoList of Enums (see below)Specify the OS on which the Prisma Client will run to ensure compatibility of the query engine. Default: native
moduleFormatNoEnum (cjs or esm)Defines the module format of the generated Prisma Client. This field is available only with prisma-client generator.

Fields for prisma-client provider

The ESM-first client generator that offers greater control and flexibility across different JavaScript environments. It generates plain TypeScript code into a custom directory, providing full visibility over the generated code. Learn more about the new prisma-client generator.

A generator block accepts the following fields:

NameRequiredTypeDescription
providerYesprisma-clientDescribes which generator to use. This can point to a file that implements a generator or specify a built-in generator directly.
outputYesString (file path)Determines the location for the generated client, learn more.
previewFeaturesNoList of EnumsUse intellisense to see list of currently available Preview features (Ctrl+Space in Visual Studio Code) Default: none
runtimeNoEnum (nodejs, deno, bun, workerd (alias cloudflare), vercel-edge (alias edge-light), react-native)Target runtime environment. Default: nodejs
moduleFormatNoEnum (esm or cjs)Determines whether the generated code supports ESM (uses import) or CommonJS (uses require(...)) modules. We always recommend esm unless you have a good reason to use cjs. Default: Inferred from environment.
generatedFileExtensionNoEnum (ts or mts or cts)File extension for generated TypeScript files. Default: ts
importFileExtensionNoEnum (ts,mts,cts,js,mjs,cjs, empty (for bare imports))File extension used in import statements Default: Inferred from environment.
compilerBuildNoString (fast, small)Defines what build of the query compiler to use for the generated client. fast, the default, gives you fast query compilation, but with an increase in size. small gives you the smallest size, but with a slightly slower execution.

binaryTargets options

The following tables list all supported operating systems with the name of platform to specify in binaryTargets.

Unless specified otherwise, the default supported CPU architecture is x86_64.

macOS
Build OSPrisma engine build name
macOS Intel x86_64darwin
macOS ARM64darwin-arm64
Windows
Build OSPrisma engine build name
Windowswindows
Linux (Alpine on x86_64 architectures)
Build OSPrisma engine build nameOpenSSL
Alpine (3.17 and newer)linux-musl-openssl-3.0.x3.0.x
Alpine (3.16 and older)linux-musl1.1.x
Linux (Alpine on ARM64 architectures)
Build OSPrisma engine build nameOpenSSL
Alpine (3.17 and newer)linux-musl-arm64-openssl-3.0.x3.0.x
Alpine (3.16 and older)linux-musl-arm64-openssl-1.1.x1.1.x
Linux (Debian), x86_64
Build OSPrisma engine build nameOpenSSL
Debian 8 (Jessie)debian-openssl-1.0.x1.0.x
Debian 9 (Stretch)debian-openssl-1.1.x1.1.x
Debian 10 (Buster)debian-openssl-1.1.x1.1.x
Debian 11 (Bullseye)debian-openssl-1.1.x1.1.x
Debian 12 (Bookworm)debian-openssl-3.0.x3.0.x
Linux (Ubuntu), x86_64
Build OSPrisma engine build nameOpenSSL
Ubuntu 14.04 (trusty)debian-openssl-1.0.x1.0.x
Ubuntu 16.04 (xenial)debian-openssl-1.0.x1.0.x
Ubuntu 18.04 (bionic)debian-openssl-1.1.x1.1.x
Ubuntu 19.04 (disco)debian-openssl-1.1.x1.1.x
Ubuntu 20.04 (focal)debian-openssl-1.1.x1.1.x
Ubuntu 21.04 (hirsute)debian-openssl-1.1.x1.1.x
Ubuntu 22.04 (jammy)debian-openssl-3.0.x3.0.x
Ubuntu 23.04 (lunar)debian-openssl-3.0.x3.0.x
Linux (CentOS), x86_64
Build OSPrisma engine build nameOpenSSL
CentOS 7rhel-openssl-1.0.x1.0.x
CentOS 8rhel-openssl-1.1.x1.1.x
Linux (Fedora), x86_64
Build OSPrisma engine build nameOpenSSL
Fedora 28rhel-openssl-1.1.x1.1.x
Fedora 29rhel-openssl-1.1.x1.1.x
Fedora 30rhel-openssl-1.1.x1.1.x
Fedora 36rhel-openssl-3.0.x3.0.x
Fedora 37rhel-openssl-3.0.x3.0.x
Fedora 38rhel-openssl-3.0.x3.0.x
Linux (Linux Mint), x86_64
Build OSPrisma engine build nameOpenSSL
Linux Mint 18debian-openssl-1.0.x1.0.x
Linux Mint 19debian-openssl-1.1.x1.1.x
Linux Mint 20debian-openssl-1.1.x1.1.x
Linux Mint 21debian-openssl-3.0.x3.0.x
Linux (Arch Linux), x86_64
Build OSPrisma engine build nameOpenSSL
Arch Linux 2019.09.01debian-openssl-1.1.x1.1.x
Arch Linux 2023.04.23debian-openssl-3.0.x3.0.x
Linux ARM64 (all major distros but Alpine)
Build OSPrisma engine build nameOpenSSL
Linux ARM64 glibc-based distrolinux-arm64-openssl-1.0.x1.0.x
Linux ARM64 glibc-based distrolinux-arm64-openssl-1.1.x1.1.x
Linux ARM64 glibc-based distrolinux-arm64-openssl-3.0.x3.0.x

Examples

Specify the prisma-client-js generator with the default output, previewFeatures, engineType and binaryTargets

generator client {
  provider = "prisma-client-js"
}

Note that the above generator definition is equivalent to the following because it uses the default values for output, engineType and binaryTargets (and implicitly previewFeatures):

generator client {
  provider      = "prisma-client-js"
  output        = "node_modules/.prisma/client"
  engineType    = "library"
  binaryTargets = ["native"]
}

Specify a custom output location for Prisma Client

This example shows how to define a custom output location of the generated asset to override the default one.

generator client {
  provider = "prisma-client-js"
  output   = "../src/generated/client"
}

Specify custom binaryTargets to ensure compatibility with the OS

This example shows how to configure Prisma Client to run on Ubuntu 19.04 (disco) based on the table above.

generator client {
  provider      = "prisma-client-js"
  binaryTargets = ["debian-openssl-1.1.x"]
}

Specify a provider pointing to some custom generator implementation

This example shows how to use a custom generator that's located in a directory called my-generator.

generator client {
  provider = "./my-generator"
}

Defines a Prisma model .

Naming conventions

Note: You can use the @@map attribute to map a model (for example, User) to a table with a different name that does not match model naming conventions (for example, users).

Order of fields

Examples

A model named User with two scalar fields

Fields are properties of models.

Naming conventions

Note: You can use the @map attribute to map a field name to a column with a different name that does not match field naming conventions: e.g. myField @map("my_field").

The data source connector determines what native database type each of Prisma ORM scalar type maps to. Similarly, the generator determines what type in the target programming language each of these types map to.

Prisma models also have model field types that define relations between models.

String

Variable length text.

Default type mappings

ConnectorDefault mapping
PostgreSQLtext
SQL Servernvarchar(1000)
MySQLvarchar(191)
MongoDBString
SQLiteTEXT
CockroachDBSTRING

PostgreSQL

Native database typeNative database type attributeNotes
text@db.Text
char(x)@db.Char(x)
varchar(x)@db.VarChar(x)
bit(x)@db.Bit(x)
varbit@db.VarBit
uuid@db.Uuid
xml@db.Xml
inet@db.Inet
citext@db.CitextOnly available if Citext extension is enabled.

MySQL

Native database typeNative database type attribute
VARCHAR(x)@db.VarChar(x)
TEXT@db.Text
CHAR(x)@db.Char(x)
TINYTEXT@db.TinyText
MEDIUMTEXT@db.MediumText
LONGTEXT@db.LongText

You can use Prisma Migrate to map @db.Bit(1) to String:

model Model {
  /* ... */
  myField String @db.Bit(1)
}

MongoDB

String

Native database type attributeNotes
@db.String
@db.ObjectIdRequired if the underlying BSON type is OBJECT_ID (ID fields, relation scalars)

Microsoft SQL Server

Native database typeNative database type attribute
char(x)@db.Char(x)
nchar(x)@db.NChar(x)
varchar(x)@db.VarChar(x)
nvarchar(x)@db.NVarChar(x)
text@db.Text
ntext@db.NText
xml@db.Xml
uniqueidentifier@db.UniqueIdentifier

SQLite

TEXT

CockroachDB

Native database typeNative database type attributeNotes
STRING(x)TEXT(x)VARCHAR(x)
CHAR(x)@db.Char(x)
"char"@db.CatalogSingleChar
BIT(x)@db.Bit(x)
VARBIT@db.VarBit
UUID@db.Uuid
INET@db.Inet

Note that the xml and citext types supported in PostgreSQL are not currently supported in CockroachDB.

Clients

Boolean

True or false value.

Default type mappings

ConnectorDefault mapping
PostgreSQLboolean
SQL Serverbit
MySQLTINYINT(1)
MongoDBBool
SQLiteINTEGER
CockroachDBBOOL

PostgreSQL

Native database typesNative database type attributeNotes
boolean@db.Boolean

MySQL

Native database typesNative database type attributeNotes
TINYINT(1)@db.TinyInt(1)TINYINT maps to Int if the max length is greater than 1 (for example, TINYINT(2)) or the default value is anything other than 1, 0, or NULL
BIT(1)@db.Bit

MongoDB

Bool

Microsoft SQL Server

Native database typesNative database type attributeNotes
bit@db.Bit

SQLite

INTEGER

CockroachDB

Native database typesNative database type attributeNotes
BOOL@db.Bool

Clients

Int

Default type mappings

ConnectorDefault mapping
PostgreSQLinteger
SQL Serverint
MySQLINT
MongoDBInt
SQLiteINTEGER
CockroachDBINT

PostgreSQL

Native database typesNative database type attributeNotes
integerint, int4@db.Integer
smallintint2@db.SmallInt
smallserialserial2@db.SmallInt @default(autoincrement())
serialserial4@db.Int @default(autoincrement())
oid@db.Oid

MySQL

Native database typesNative database type attributeNotes
INT@db.Int
INT UNSIGNED@db.UnsignedInt
SMALLINT@db.SmallInt
SMALLINT UNSIGNED@db.UnsignedSmallInt
MEDIUMINT@db.MediumInt
MEDIUMINT UNSIGNED@db.UnsignedMediumInt
TINYINT@db.TinyIntTINYINT maps to Int if the max length is greater than 1 (for example, TINYINT(2)) or the default value is anything other than 1, 0, or NULL. TINYINT(1) maps to Boolean.
TINYINT UNSIGNED@db.UnsignedTinyIntTINYINT(1) UNSIGNED maps to Int, not Boolean
YEAR@db.Year

MongoDB

Int

Native database type attributeNotes
@db.Int
@db.Long

Microsoft SQL Server

Native database typesNative database type attributeNotes
int@db.Int
smallint@db.SmallInt
tinyint@db.TinyInt
bit@db.Bit

SQLite

INTEGER

CockroachDB

Native database typesNative database type attributeNotes
INTEGERINTINT8
INT4@db.Int4
INT2SMALLINT@db.Int2
SMALLSERIALSERIAL2@db.Int2 @default(autoincrement())
SERIALSERIAL4@db.Int4 @default(autoincrement())
SERIAL8BIGSERIAL@db.Int8 @default(autoincrement())

Clients

BigInt

Default type mappings

ConnectorDefault mapping
PostgreSQLbigint
SQL Serverint
MySQLBIGINT
MongoDBLong
SQLiteINTEGER
CockroachDBINTEGER

PostgreSQL

Native database typesNative database type attributeNotes
bigintint8@db.BigInt
bigserialserial8@db.BigInt @default(autoincrement())

MySQL

Native database typesNative database type attributeNotes
BIGINT@db.BigInt
SERIAL@db.UnsignedBigInt @default(autoincrement())

MongoDB

Long

Microsoft SQL Server

Native database typesNative database type attributeNotes
bigint@db.BigInt

SQLite

INTEGER

CockroachDB

Native database typesNative database type attributeNotes
BIGINTINTINT8
bigserialserial8@db.Int8 @default(autoincrement())

Clients

Float

Floating point number.

Default type mappings

ConnectorDefault mapping
PostgreSQLdouble precision
SQL Serverfloat(53)
MySQLDOUBLE
MongoDBDouble
SQLiteREAL
CockroachDBDOUBLE PRECISION

PostgreSQL

Native database typesNative database type attributeNotes
double precision@db.DoublePrecision
real@db.Real

MySQL

Native database typesNative database type attributeNotes
FLOAT@db.Float
DOUBLE@db.Double

MongoDB

Double

Microsoft SQL Server

Native database typesNative database type attribute
float@db.Float
money@db.Money
smallmoney@db.SmallMoney
real@db.Real

SQLite connector

REAL

CockroachDB

Native database typesNative database type attributeNotes
DOUBLE PRECISIONFLOAT8@db.Float8
REALFLOAT4FLOAT

Clients

Decimal

Default type mappings

ConnectorDefault mapping
PostgreSQLdecimal(65,30)
SQL Serverdecimal(32,16)
MySQLDECIMAL(65,30)
MongoDBNot supported
SQLiteDECIMAL
CockroachDBDECIMAL

PostgreSQL

Native database typesNative database type attributeNotes
decimalnumeric@db.Decimal(p, s)
money@db.Money

MySQL

Native database typesNative database type attributeNotes
DECIMALNUMERIC@db.Decimal(p, s)

MongoDB

Not supported.

Microsoft SQL Server

Native database typesNative database type attributeNotes
decimalnumeric@db.Decimal(p, s)

SQLite

DECIMAL (changed from REAL in 2.17.0)

CockroachDB

Native database typesNative database type attributeNotes
DECIMALDECNUMERIC
moneyNot yetPostgreSQL's money type is not yet supported by CockroachDB

Clients

DateTime

You can find more info and examples in this section: Working with DateTime.

Default type mappings

ConnectorDefault mapping
PostgreSQLtimestamp(3)
SQL Serverdatetime2
MySQLDATETIME(3)
MongoDBTimestamp
SQLiteNUMERIC
CockroachDBTIMESTAMP

PostgreSQL

Native database typesNative database type attributeNotes
timestamp(x)@db.Timestamp(x)
timestamptz(x)@db.Timestamptz(x)
date@db.Date
time(x)@db.Time(x)
timetz(x)@db.Timetz(x)

MySQL

Native database typesNative database type attributeNotes
DATETIME(x)@db.DateTime(x)
DATE(x)@db.Date(x)
TIME(x)@db.Time(x)
TIMESTAMP(x)@db.Timestamp(x)

You can also use MySQL's YEAR type with Int:

yearField     Int    @db.Year

MongoDB

Timestamp

Microsoft SQL Server

Native database typesNative database type attributeNotes
date@db.Date
time@db.Time
datetime@db.DateTime
datetime2@db.DateTime2
smalldatetime@db.SmallDateTime
datetimeoffset@db.DateTimeOffset

SQLite

NUMERIC or STRING. If the underlying data type is STRING, you must use one of the following formats:

CockroachDB

Native database typesNative database type attributeNotes
TIMESTAMP(x)@db.Timestamp(x)
TIMESTAMPTZ(x)@db.Timestamptz(x)
DATE@db.Date
TIME(x)@db.Time(x)
TIMETZ(x)@db.Timetz(x)

Clients

Json

A JSON object.

Default type mappings

PostgreSQL

Native database typesNative database type attributeNotes
json@db.Json
jsonb@db.JsonB

MySQL

Native database typesNative database type attributeNotes
JSON@db.Json

MongoDB

A valid BSON object (Relaxed mode)

Microsoft SQL Server

Microsoft SQL Server does not have a specific data type for JSON. However, there are a number of built-in functions for reading and modifying JSON.

SQLite

Not supported

CockroachDB

Native database typesNative database type attributeNotes
JSONJSONB@db.JsonB

Clients

Bytes

Default type mappings

ConnectorDefault mapping
PostgreSQLbytea
SQL Servervarbinary
MySQLLONGBLOB
MongoDBBinData
SQLiteBLOB
CockroachDBBYTES

PostgreSQL

Native database typesNative database type attribute
bytea@db.ByteA

MySQL

Native database typesNative database type attributeNotes
LONGBLOB@db.LongBlob
BINARY@db.Binary
VARBINARY@db.VarBinary
TINYBLOB@db.TinyBlob
BLOB@db.Blob
MEDIUMBLOB@db.MediumBlob
BIT@db.Bit

MongoDB

BinData

Native database type attributeNotes
@db.ObjectIdRequired if the underlying BSON type is OBJECT_ID (ID fields, relation scalars)
@db.BinData

Microsoft SQL Server

Native database typesNative database type attributeNotes
binary@db.Binary
varbinary@db.VarBinary
image@db.Image

SQLite

BLOB

CockroachDB

Native database typesNative database type attribute
BYTESBYTEA

Clients

Unsupported

The Unsupported type was introduced in 2.17.0 and allows you to represent data types in the Prisma schema that are not supported by Prisma Client. Fields of type Unsupported can be created during Introspection with prisma db pull or written by hand, and created in the database with Prisma Migrate or db push.

Examples

model Star {
  id       Int                    @id @default(autoincrement())
  position Unsupported("circle")?
  example1 Unsupported("circle")
  circle   Unsupported("circle")? @default(dbgenerated("'<(10,4),11>'::circle"))
}

[] modifier

Makes a field a list.

Relational databases
MongoDB

Examples

Define a scalar list
Define a scalar list with a default value

? modifier

Makes a field optional.

Examples

Optional name field
model User {
  id   Int     @id @default(autoincrement())
  name String?
}

Attributes modify the behavior of a field or block (e.g. models). There are two ways to add attributes to your data model:

Some attributes take arguments. Arguments in attributes are always named, but in most cases the argument name can be omitted.

Note: The leading underscore in a signature means the argument name can be omitted.

@id

Defines a single-field ID on the model.

General
Relational databases
MongoDB

Arguments

NameRequiredTypeDescription
mapNoStringThe name of the underlying primary key constraint in the database.
Not supported for MySQL or MongoDB.

| | length | No | number | Allows you to specify a maximum length for the subpart of the value to be indexed.

MySQL only.

| | sort | No | String | Allows you to specify in what order the entries of the ID are stored in the database. The available options are Asc and Desc.

SQL Server only.

| | clustered | No | Boolean | Defines whether the ID is clustered or non-clustered. Defaults to true.

SQL Server only.

|

Signature

@id(map: String?, length: number?, sort: String?, clustered: Boolean?)

Examples

In most cases, you want your database to create the ID. To do this, annotate the ID field with the @default attribute and initialize the field with a function.

Generate autoincrementing integers as IDs (Relational databases only)
model User {
  id   Int    @id @default(autoincrement())
  name String
}
Generate ObjectId as IDs (MongoDB only)
model User {
  id   String @id @default(auto()) @map("_id") @db.ObjectId
  name String
}
Generate cuid() values as IDs
Generate uuid() values as IDs
Generate ulid() values as IDs
Single-field IDs without default values

In the following example, id does not have a default value:

model User {
id    String   @id  @map("_id")
name  String
}

Note that in the above case, you must provide your own ID values when creating new records for the User model using Prisma Client, e.g.:

const newUser = await prisma.user.create({
  data: {
    id: 1,
    name: "Alice",
  },
});
Specify an ID on relation scalar field without a default value

In the following example, authorId is a both a relation scalar and the ID of Profile:

In this scenario, you cannot create a Profile only - you must use Prisma Client's nested writes create a User or connect the profile to an existing user.

The following example creates a user and a profile:

const userWithProfile = await prisma.user.create({
  data: {
    id: 3,
    email: "bob@prisma.io",
    name: "Bob Prismo",
    profile: {
      create: {
        bio: "Hello, I'm Bob Prismo and I love apples, blue nail varnish, and the sound of buzzing mosquitoes.",
      },
    },
  },
});

The following example connects a new profile to a user:

const profileWithUser = await prisma.profile.create({
  data: {
    bio: "Hello, I'm Bob and I like nothing at all. Just nothing.",
    author: {
      connect: {
        id: 22,
      },
    },
  },
});

@@id

Defines a multi-field ID (composite ID) on the model.

Arguments

NameRequiredTypeDescription
fieldsYesFieldReference[]A list of field names - for example, ["firstname", "lastname"]
nameNoStringThe name that Prisma Client will expose for the argument covering all fields, e.g. fullName in fullName: { firstName: "First", lastName: "Last"}
mapNoStringThe name of the underlying primary key constraint in the database.
Not supported for MySQL.

| | length | No | number | Allows you to specify a maximum length for the subpart of the value to be indexed.

MySQL only.

| | sort | No | String | Allows you to specify in what order the entries of the ID are stored in the database. The available options are Asc and Desc.

SQL Server only.

| | clustered | No | Boolean | Defines whether the ID is clustered or non-clustered. Defaults to true.

SQL Server only.

|

The name of the fields argument on the @@id attribute can be omitted:

@@id(fields: [title, author])
@@id([title, author])

Signature

@@id(_ fields: FieldReference[], name: String?, map: String?)

Examples

Specify a multi-field ID on two String fields (Relational databases only)
model User {
  firstName String
  lastName  String
  email     String  @unique
  isAdmin   Boolean @default(false)

  @@id([firstName, lastName])
}

When you create a user, you must provide a unique combination of firstName and lastName:

const user = await prisma.user.create({
  data: {
    firstName: "Alice",
    lastName: "Smith",
  },
});

To retrieve a user, use the generated composite ID field (firstName_lastName):

const user = await prisma.user.findUnique({
  where: {
    firstName_lastName: {
      firstName: "Alice",
      lastName: "Smith",
    },
  },
});
Specify a multi-field ID on two String fields and one Boolean field (Relational databases only)
model User {
  firstName String
  lastName  String
  email     String  @unique
  isAdmin   Boolean @default(false)

  @@id([firstName, lastName, isAdmin])
}

When creating new User records, you now must provide a unique combination of values for firstName, lastName and isAdmin:

const user = await prisma.user.create({
  data: {
    firstName: "Alice",
    lastName: "Smith",
    isAdmin: true,
  },
});
Specify a multi-field ID that includes a relation field (Relational databases only)
model Post {
  title     String
  published Boolean @default(false)
  author    User    @relation(fields: [authorId], references: [id])
  authorId  Int

  @@id([authorId, title])
}

model User {
  id    Int     @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

When creating new Post records, you now must provide a unique combination of values for authorId (foreign key) and title:

const post = await prisma.post.create({
  data: {
    title: "Hello World",
    author: {
      connect: {
        email: "alice@prisma.io",
      },
    },
  },
});

@default

Defines a default value for a field.

Relational databases
MongoDB

Arguments

NameRequiredTypeDescription
valueYesAn expression (e.g. 5, true, now())
mapNoStringSQL Server only.

The name of the value argument on the @default attribute can be omitted:

id Int @id @default(value: autoincrement())
id Int @id @default(autoincrement())

Signature

@default(_ value: Expression, map: String?)

Examples

Default value for an Int
Default value for a Float
Default value for Decimal
Default value for BigInt
Default value for a String
Default value for a Boolean
Default value for a DateTime

Note that static default values for DateTime are based on the ISO 8601 standard.

Default value for a Bytes
Default value for an enum
model User {
  id      Int      @id @default(autoincrement())
  email   String   @unique
  name    String?
  role    Role     @default(USER) 
  posts   Post[]
  profile Profile?
}
model User {
  id      String   @id @default(auto()) @map("_id") @db.ObjectId
  email   String   @unique
  name    String?
  role    Role     @default(USER) 
  posts   Post[]
  profile Profile?
}
Default values for scalar lists

@unique

Defines a unique constraint for this field.

General
Relational databases
MongoDB

Arguments

NameRequiredTypeDescription
mapNoString
lengthNonumberAllows you to specify a maximum length for the subpart of the value to be indexed.
MySQL only.

| | sort | No | String | Allows you to specify in what order the entries of the constraint are stored in the database. The available options are Asc and Desc. | | clustered | No | Boolean | Defines whether the constraint is clustered or non-clustered. Defaults to false.

SQL Server only.

| | where | No | function or object | Defines a partial index that only includes rows matching the specified condition. Accepts raw("SQL expression") or an object literal like { field: value }.

PostgreSQL, SQLite, SQL Server, and CockroachDB. Requires the partialIndexes Preview feature.

|

Signature

@unique(map: String?, length: number?, sort: String?, clustered: Boolean?, where: raw(String) | { field: value }?)

Note: The where argument accepts either raw("SQL expression") for raw SQL predicates or an object literal like { field: value } for type-safe conditions. See Configuring partial indexes for details.

Note: Before the partialIndexes Preview feature, the signature was:

@unique(map: String?, length: number?, sort: String?, clustered: Boolean?)

Examples

Specify a unique attribute on a required String field
Specify a unique attribute on an optional String field
Specify a unique attribute with cuid() values as default values

@@unique

Defines a compound unique constraint for the specified fields.

General
Relational databases
MongoDB

Arguments

NameRequiredTypeDescription
fieldsYesFieldReference[]A list of field names - for example, ["firstname", "lastname"]. Fields must be mandatory - see remarks.
nameNoStringThe name of the unique combination of fields - defaults to fieldName1_fieldName2_fieldName3
mapNoString
lengthNonumberAllows you to specify a maximum length for the subpart of the value to be indexed.
MySQL only.

| | sort | No | String | Allows you to specify in what order the entries of the constraint are stored in the database. The available options are Asc and Desc. | | clustered | No | Boolean | Defines whether the constraint is clustered or non-clustered. Defaults to false.

SQL Server only.

| | where | No | function or object | Defines a partial index that only includes rows matching the specified condition. Accepts raw("SQL expression") or an object literal like { field: value }.

PostgreSQL, SQLite, SQL Server, and CockroachDB. Requires the partialIndexes Preview feature.

|

The name of the fields argument on the @@unique attribute can be omitted:

@@unique(fields: [title, author])
@@unique([title, author])
@@unique(fields: [title, author], name: "titleAuthor")

The length and sort arguments are added to the relevant field names:

@@unique(fields: [title(length:10), author])
@@unique([title(sort: Desc), author(sort: Asc)])

Signature

@@unique(_ fields: FieldReference[], name: String?, map: String?, where: raw(String) | { field: value }?)

Note: The where argument accepts either raw("SQL expression") for raw SQL predicates or an object literal like { field: value } for type-safe conditions. See Configuring partial indexes for details.

Note: Before the partialIndexes Preview feature (and before version 4.0.0 / 3.5.0 with the extendedIndexes Preview feature), the signature was:

@@unique(_ fields: FieldReference[], name: String?, map: String?)

Examples

Specify a multi-field unique attribute on two String fields

To retrieve a user, use the generated field name (firstname_lastname):

const user = await prisma.user.findUnique({
  where: {
    firstName_lastName: {
      firstName: "Alice",
      lastName: "Smith",
      isAdmin: true,
    },
  },
});
Specify a multi-field unique attribute on two String fields and one Boolean field
Specify a multi-field unique attribute that includes a relation field
Specify a custom name for a multi-field unique attribute

To retrieve a user, use the custom field name (admin_identifier):

const user = await prisma.user.findUnique({
  where: {
    admin_identifier: {
      firstName: "Alice",
      lastName: "Smith",
      isAdmin: true,
    },
  },
});

@@index

Defines an index in the database.

Relational databases
MongoDB

Arguments

NameRequiredTypeDescription
fieldsYesFieldReference[]A list of field names - for example, ["firstname", "lastname"]
nameNoStringThe name that Prisma Client will expose for the argument covering all fields, e.g. fullName in fullName: { firstName: "First", lastName: "Last"}
mapNomapThe name of the index in the underlying database (Prisma generates an index name that respects identifier length limits if you do not specify a name. Prisma uses the following naming convention: tablename.field1_field2_field3_unique)
lengthNonumberAllows you to specify a maximum length for the subpart of the value to be indexed.
MySQL only.

| | sort | No | String | Allows you to specify in what order the entries of the index or constraint are stored in the database. The available options are asc and desc. | | clustered | No | Boolean | Defines whether the index is clustered or non-clustered. Defaults to false.

SQL Server only.

| | type | No | identifier | Allows you to specify an index access method. Defaults to BTree.

PostgreSQL and CockroachDB only.

| | ops | No | identifier or a function | Allows you to define the index operators for certain index types.

PostgreSQL only.

| | where | No | function or object | Defines a partial index that only includes rows matching the specified condition. Accepts raw("SQL expression") or an object literal like { field: value }.

PostgreSQL, SQLite, SQL Server, and CockroachDB. Requires the partialIndexes Preview feature.

|

The name of the fields argument on the @@index attribute can be omitted:

@@index(fields: [title, author])
@@index([title, author])

The length and sort arguments are added to the relevant field names:

@@index(fields: [title(length:10), author])
@@index([title(sort: Asc), author(sort: Desc)])

Signature

@@index(_ fields: FieldReference[], map: String?, where: raw(String) | { field: value }?)

Note: The where argument accepts either raw("SQL expression") for raw SQL predicates or an object literal like { field: value } for type-safe conditions. See Configuring partial indexes for details.

Note: With the partialIndexes Preview feature, the where argument is available. Before this Preview feature, the signature was:

@@index(_ fields: FieldReference[], map: String?)

Examples

Assume you want to add an index for the title field of the Post model

Define a single-column index (Relational databases only)
model Post {
  id      Int     @id @default(autoincrement())
  title   String
  content String?

  @@index([title])
}
Define a multi-column index (Relational databases only)
model Post {
  id      Int     @id @default(autoincrement())
  title   String
  content String?

  @@index([title, content])
}
Define an index with a name (Relational databases only)
model Post {
  id      Int     @id @default(autoincrement())
  title   String
  content String?

  @@index(fields: [title, content], name: "main_index")
}
Define an index on a composite type field (Relational databases only)
type Address {
  street String
  number Int
}

model User {
  id      Int     @id
  email   String
  address Address

  @@index([address.number])
}

@relation

Defines meta information about the relation. Learn more.

Relational databases
MongoDB

Arguments

NameTypeRequiredDescriptionExample
nameStringSometimes (e.g. to disambiguate a relation)Defines the name of the relationship. In an m-n-relation, it also determines the name of the underlying relation table."CategoryOnPost", "MyRelation"
fieldsFieldReference[]On annotated relation fieldsA list of fields of the current model["authorId"], ["authorFirstName, authorLastName"]
referencesFieldReference[]On annotated relation fieldsA list of fields of the model on the other side of the relation["id"], ["firstName, lastName"]
mapStringNoDefines a custom name for the foreign key in the database.["id"], ["firstName, lastName"]
onUpdateEnum. See Types of referential actions for values.NoDefines the referential action to perform when a referenced entry in the referenced model is being updated.Cascade, NoAction
onDeleteEnum. See Types of referential actions for values.NoDefines the referential action to perform when a referenced entry in the referenced model is being deleted.Cascade, NoAction

The name of the name argument on the @relation attribute can be omitted (references is required):

@relation(name: "UserOnPost", references: [id])
@relation("UserOnPost", references: [id])

// or

@relation(name: "UserOnPost")
@relation("UserOnPost")

Signature

@relation(_ name: String?, fields: FieldReference[]?, references: FieldReference[]?, onDelete: ReferentialAction?, onUpdate: ReferentialAction?, map: String?)

With SQLite, the signature changes to:

@relation(_ name: String?, fields: FieldReference[]?, references: FieldReference[]?, onDelete: ReferentialAction?, onUpdate: ReferentialAction?)

Examples

See: The @relation attribute.

@map

Maps a field name or enum value from the Prisma schema to a column or document field with a different name in the database. If you do not use @map, the Prisma field name matches the column name or document field name exactly.

See Using custom model and field names to see how @map and @@map changes the generated Prisma Client.

General
MongoDB

Your @id field must include @map("_id"). For example:

model User {
  id String @default(auto()) @map("_id") @db.ObjectId
}

Arguments

NameTypeRequiredDescriptionExample
nameStringYesThe database column (relational databases) or document field (MongoDB) name."comments", "someFieldName"

The name of the name argument on the @map attribute can be omitted:

@map(name: "is_admin")
@map("users")

Signature

@map(_ name: String)

Examples

Map the firstName field to a column called first_name

The generated client:

await prisma.user.create({
  data: {
    firstName: "Yewande", // first_name */} firstName
  },
});
Map an enum named ADMIN to a database enum named admin
enum Role {
  ADMIN    @map("admin")
  CUSTOMER
}

In Prisma ORM v7 and later, the generated TypeScript enum uses the mapped values:

export const Role = {
  ADMIN: "admin",
  CUSTOMER: "CUSTOMER",
} as const;

This means Role.ADMIN evaluates to "admin", not "ADMIN".

@@map

Maps the Prisma schema model name to a table (relational databases) or collection (MongoDB) with a different name, or an enum name to a different underlying enum in the database. If you do not use @@map, the model name matches the table (relational databases) or collection (MongoDB) name exactly.

See Using custom model and field names to see how @map and @@map changes the generated Prisma Client.

Arguments

NameTypeRequiredDescriptionExample
nameStringYesThe database table (relational databases) or collection (MongoDB) name."comments", "someTableOrCollectionName"

The name of the name argument on the @@map attribute can be omitted

@@map(name: "users")
@@map("users")

Signature

@@map(_ name: String)

Examples

Map the User model to a database table/collection named users

The generated client:

await prisma.user.create({
  // users */} user
  data: {
    name: "Yewande",
  },
});
Map the Role enum to a native enum in the database named _Role its values to lowercase values in the database
enum Role {
  ADMIN    @map("admin")
  CUSTOMER @map("customer")

  @@map("_Role")
}

@updatedAt

Automatically stores the time when a record was last updated. If you do not supply a time yourself, Prisma Client will automatically set the value for fields with this attribute.

Arguments

N/A

Signature

@updatedAt

Examples

@ignore

Add @ignore to a field that you want to exclude from Prisma Client (for example, a field that you do not want Prisma Client users to update). Ignored fields are excluded from the generated Prisma Client. The model's create method is disabled when doing this for required fields with no @default (because the database cannot create an entry without that data).

Examples

The following example demonstrates manually adding @ignore to exclude the email field from Prisma Client:

schema.prisma

model User {
  id    Int    @id
  name  String
  email String @ignore // this field will be excluded
}

@@ignore

Add @@ignore to a model that you want to exclude from Prisma Client (for example, a model that you do not want Prisma users to update). Ignored models are excluded from the generated Prisma Client.

Examples

In the following example, the Post model is invalid because it does not have a unique identifier. Use @@ignore to exclude it from the generated Prisma Client API:

schema.prisma

/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by Prisma Client.
model Post {
  id       Int  @default(autoincrement()) // no unique identifier
  author   User @relation(fields: [authorId], references: [id])
  authorId Int

  @@ignore
}

In the following example, the Post model is invalid because it does not have a unique identifier, and the posts relation field on User is invalid because it refers to the invalid Post model. Use @@ignore on the Post model and @ignore on the posts relation field in User to exclude both the model and the relation field from the generated Prisma Client API:

schema.prisma

/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by Prisma Client.
model Post {
  id       Int  @default(autoincrement()) // no unique identifier
  author   User @relation(fields: [authorId], references: [id])
  authorId Int

  @@ignore
}

model User {
  id    Int     @id @default(autoincrement())
  name  String?
  posts Post[]  @ignore
}

@@schema

Add @@schema to a model to specify which schema in your database should contain the table associated with that model. Learn more about adding multiple schema's here.

Arguments

NameTypeRequiredDescriptionExample
nameStringYesThe name of the database schema."base", "auth"

The name of the name argument on the @@schema attribute can be omitted

@@schema(name: "auth")
@@schema("auth")

Signature

@@schema(_ name: String)

Examples

Map the User model to a database schema named auth
generator client {
  provider        = "prisma-client"
  output          = "./generated"
}

datasource db {
  provider = "postgresql"
  schemas  = ["auth"] 
}

model User {
  id   Int    @id @default(autoincrement())
  name String

  @@schema("auth") 
}

@shardKey

The @shardKey attribute is only compatible with PlanetScale databases. It enables you define a shard key on a field of your model:

model User {
  id     String @default(uuid())
  region String @shardKey
}

@@shardKey

The @@shardKey attribute is only compatible with PlanetScale databases. It enables you define a shard key on multiple fields of your model:

model User {
  id         String @default(uuid())
  country    String
  customerId String
  @@shardKey([country, customerId])
}

auto()

Represents default values that are automatically generated by the database.

MongoDB

Used to generate an ObjectId for @id fields:

id  String  @map("_id") @db.ObjectId @default(auto())
Relational databases

The auto() function is not available on relational databases.

Example

Generate ObjectId (MongoDB only)
model User {
  id   String  @id @default(auto()) @map("_id") @db.ObjectId
  name String?
}

autoincrement()

Create a sequence of integers in the underlying database and assign the incremented values to the ID values of the created records based on the sequence.

Examples

Generate autoincrementing integers as IDs (Relational databases only)
model User {
  id   Int    @id @default(autoincrement())
  name String
}

sequence()

Create a sequence of integers in the underlying database and assign the incremented values to the values of the created records based on the sequence.

Optional arguments

ArgumentExample
virtual@default(sequence(virtual))
Virtual sequences are sequences that do not generate monotonically increasing values and instead produce values like those generated by the built-in function unique_rowid().
cache@default(sequence(cache: 20))
The number of sequence values to cache in memory for reuse in the session. A cache size of 1 means that there is no cache, and cache sizes of less than 1 are not valid.
increment@default(sequence(increment: 4))
The new value by which the sequence is incremented. A negative number creates a descending sequence. A positive number creates an ascending sequence.
minValue@default(sequence(minValue: 10))
The new minimum value of the sequence.
maxValue@default(sequence(maxValue: 3030303))
The new maximum value of the sequence.
start@default(sequence(start: 2))
The value the sequence starts at, if it's restarted or if the sequence hits the maxValue.

Examples

Generate sequencing integers as IDs
model User {
  id   Int    @id @default(sequence(maxValue: 4294967295))
  name String
}

cuid()

Generate a globally unique identifier based on the cuid spec.

If you'd like to use cuid2 values, you can pass 2 as an argument to the cuid function: cuid(2).

Examples

Generate cuid() values as IDs
Generate cuid(2) values as IDs based on the cuid2 spec

uuid()

Generate a globally unique identifier based on the UUID spec. Prisma ORM supports versions 4 (default) and 7.

Examples

Generate uuid() values as IDs using UUID v4
Generate uuid(7) values as IDs using UUID v7

ulid()

Generate a universally unique lexicographically sortable identifier based on the ULID spec.

Examples

Generate ulid() values as IDs

nanoid()

Generated values based on the Nano ID spec. nanoid() accepts an integer value between 2 and 255 that specifies the length of the generate ID value, e.g. nanoid(16) will generated ID with 16 characters. If you don't provide a value to the nanoid() function, the default value is 21.

Examples

Generate nanoid() values with 21 characters as IDs
Generate nanoid() values with 16 characters as IDs

now()

Set a timestamp of the time when a record is created.

General
Relational databases
MongoDB

Examples

Set current timestamp value when a record is created

dbgenerated(...)

Represents default values that cannot be expressed in the Prisma schema (such as random()).

Relational databases

Examples

Set default value for Unsupported type
circle     Unsupported("circle")?   @default(dbgenerated("'<(10,4),11>'::circle"))
Override default value behavior for supported types

You can also use dbgenerated(...) to set the default value for supported types. For example, in PostgreSQL you can generate UUIDs at the database level rather than rely on Prisma ORM's uuid():

model User {
  id   String  @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
  id   String  @id @default(uuid()) @db.Uuid
  test String?
}

FieldReference[]

An array of field names: [id], [firstName, lastName]

String

A variable length text in double quotes: "", "Hello World", "Alice"

Expression

An expression that can be evaluated by Prisma ORM: 42.0, "", Bob, now(), cuid()

Defines an enum .

Naming conventions

Examples

Specify an enum with two possible values

Specify an enum with two possible values and set a default value

Defines a composite type.

Naming conventions

Type names must:

Examples

Define a Product model with a list of Photo composite types

model Product {
  id     String  @id @default(auto()) @map("_id") @db.ObjectId
  name   String
  photos Photo[]
}

type Photo {
  height Int
  width  Int
  url    String
}