Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 36 ยท Schema and Models

Models and Fields in the Prisma Schema

Learn the Prisma schema language: how models become tables, how fields, optional and list types, default values and comments work, with a SQL-generating stand-in.

The Prisma schema is a small, declarative language. You do not write loops or functions in it; you list models and their fields. Prisma turns that list into database tables (through migrations), TypeScript types (through generate) and Studio screens. Spend time getting good at reading and writing schemas, because everything else in Prisma builds on them.

Anatomy of a model

PRISMA
model Product {
  id          Int      @id @default(autoincrement())
  name        String
  description String?
  price       Float
  inStock     Boolean  @default(true)
  createdAt   DateTime @default(now())
}

Each field line has the shape:

TEXT
fieldName  Type  modifiers  @attributes
  • Field name: becomes the column name and the property name in TypeScript. Use camelCase.
  • Type: a scalar type (String, Int, ...), an enum, or another model (a relation).
  • Modifiers: ? makes the field optional; [] makes it a list.
  • Attributes: start with @ and refine one field (@id, @default(...), @unique). Attributes that apply to the whole model start with @@ (@@index, @@unique, @@map).

Model names are PascalCase and singular by convention (Product, not products). The client accessor is prisma.product.

Required, optional and list

PRISMA
model Profile {
  id       Int      @id @default(autoincrement())
  nickname String           // required: NOT NULL in the database
  bio      String?          // optional: can be NULL
  tags     String[]         // a list (scalar list, supported on PostgreSQL, CockroachDB, MongoDB)
}
Declaration Database TypeScript
nickname String NOT NULL string
bio String? nullable string | null
tags String[] array column string[]

Scalar lists (arrays of strings or numbers in a single column) are only available on databases with array support. On MySQL or SQLite you would model a list with a separate related model or a Json field.

A required field with no @default must be provided when you create a row; TypeScript will refuse a create call that leaves it out. An optional field can be omitted, and it will be null.

Default values

PRISMA
model Task {
  id        Int      @id @default(autoincrement())
  title     String
  done      Boolean  @default(false)
  priority  Int      @default(3)
  label     String   @default("general")
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}
  • @default(literal) supplies a constant.
  • @default(now()) stores the time of insertion.
  • @default(autoincrement()), @default(uuid()), @default(cuid()) generate ids (see the lesson on ids).
  • @updatedAt is not a default: Prisma Client sets the field to the current time on every update through the client.

Comments and documentation

PRISMA
// A normal comment: ignored by Prisma.

/// A documentation comment: copied into the generated client as JSDoc.
model Product {
  /// Price in cents, to avoid floating-point rounding.
  priceCents Int
}

Triple-slash comments show up as tooltips in your editor when you hover over the generated type. They are free documentation for your team.

Seeing what a schema becomes

This stand-in reads a miniature schema and prints the CREATE TABLE statement for SQLite, then runs it against Node's in-memory SQLite to prove it is valid. The real generator is far more capable; the point is the mapping: required to NOT NULL, optional to nullable, defaults to DEFAULT.

Node.js Stand-in: schema to CREATE TABLE

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice what the experiment proves: a required column without a default rejects an insert that leaves it out, the optional column became null and the defaults filled themselves in. That is the same behaviour you get from the real tables Prisma creates.

Naming guidelines

  1. Models: singular PascalCase (OrderItem). Fields: camelCase (unitPrice).
  2. Avoid reserved words in models: do not call a model Model, Client or a name that clashes with a JavaScript global you will import.
  3. Booleans read well as questions: isActive, hasPaid, published.
  4. Timestamps end in At (createdAt, deletedAt); dates without a time end in On or Date (bornOn).
  5. Store money as integer cents or as Decimal, never Float (see the next lesson).

A schema is also documentation

Because it is short and declarative, new team members can read schema.prisma and understand the whole data model in minutes. Keep it tidy with prisma format, group related models together and use /// comments to record decisions ("prices include VAT").

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a ? after a field type mean, as in bio String?

    A question mark makes the field optional. In the database it is nullable; in TypeScript the type is string | null.
  2. 2. Which attribute sets a timestamp automatically every time the row is updated through Prisma Client?

    @updatedAt makes Prisma Client write the current time whenever the record is updated. @default(now()) only runs on insert.
  3. 3. How is a model called BlogPost reached from the client?

    The accessor lowercases the first letter of the model name.
  4. 4. What is the difference between // and /// comments in a schema?

    Triple-slash comments are documentation comments that Prisma copies into the generated types.
  5. 5. Where do attributes starting with @@ apply?

    @@ attributes such as @@index, @@unique and @@map are block-level: they describe the whole model.

Summary

  • A model has fields written as name Type modifiers @attributes.
  • ? means optional, [] means list; required fields without defaults must be supplied on create.
  • @default(...) and @updatedAt fill values automatically; @@ attributes apply to the whole model.
  • Follow naming conventions and document decisions with /// comments.

Next: Field Types and Attributes