In Prisma 7, how do @@id, @@unique and @@index differ, and how does a composite key show up in a findUnique call?
answer
- block attributes over several fields
- one id, many uniques, many indexes
- field names joined by underscores
- name: for the client, map: for the database
basics
~20 s@@id makes several fields the primary key, @@unique adds a multi-column unique index, and @@index adds a plain lookup index. The first two give Prisma Client a compound selector such as authorId_slug for findUnique; @@index gives none.
solid answer
~40 sAll three are **block attributes**: they sit at the bottom of a model and list fields, as in `@@id([authorId, slug])`. A model has at most one id, so `@@id` replaces a single `@id`, while it may carry any number of `@@unique` and `@@index` blocks. `@@id` and `@@unique` are unique criteria, so Prisma Client generates a **compound selector** named after the fields joined by underscores: `findUnique({ where: { authorId_slug: { authorId: 7, slug: "hello" } } })`. The `name:` argument renames that selector (`@@id([authorId, slug], name: "postKey")`), and `map:` names the database constraint instead. `@@index` creates a non-unique index for lookups and adds nothing to the unique-where type; on PostgreSQL it also takes `type:` (`Hash`, `Gin`, `Gist`, `SpGist`, `Brin`, default `BTree`). Default names come from the table and columns: `Post_pkey`, `Post_title_locale_key`, `Post_published_title_idx`.
code
typescript · 16 linesimport { PrismaClient } from "./generated/prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";
const prisma = new PrismaClient({
adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
});
// @@id([authorId, slug]) generates the authorId_slug selector
const post = await prisma.post.findUnique({
where: { authorId_slug: { authorId: 7, slug: "hello-prisma" } },
});
// @@unique([title, locale]) generates the title_locale selector
const translated = await prisma.post.findUnique({
where: { title_locale: { title: "Hello", locale: "de" } },
});go deeper
Remember that @@ attributes span several fields: @@id is the composite primary key, @@unique forbids duplicate combinations, and @@index only speeds up lookups.
Explain how @@id and @@unique become compound selectors named field1_field2, how name: and map: differ, and why @@index adds nothing to findUnique.
Show you can read the generated constraint names, add type: Hash or Gin where PostgreSQL benefits, and know which indexes must be hand-written in migration SQL.
Set a team convention for composite keys versus surrogate ids and for index naming with map:, so selectors and constraint names stay predictable across models.
## Field attributes and block attributes Prisma's schema has two kinds of attribute. A **field attribute** starts with `@` and applies to the field it follows, such as `@id` or `@unique`. A **block attribute** starts with `@@`, sits on its own line inside the model, and takes a list of fields. The three multi-field block attributes look alike but do different jobs: | Attribute | Database object | How many per model | Unique criterion for the client | | --- | --- | --- | --- | | `@@id([a, b])` | composite primary key | at most one (and no `@id` beside it) | yes, selector `a_b` | | `@@unique([a, b])` | unique index across the columns | any number | yes, selector `a_b` | | `@@index([a, b])` | ordinary (non-unique) index | any number | no | Take a blog where a post is identified by its author and a per-author slug, titles must be unique per locale, and the feed filters by publication state: ```prisma model Post { authorId Int slug String title String locale String published Boolean @default(false) @@id([authorId, slug]) @@unique([title, locale]) @@index([published, title]) } ``` On PostgreSQL the migration creates `CONSTRAINT "Post_pkey" PRIMARY KEY ("authorId","slug")`, a unique index `Post_title_locale_key` and an index `Post_published_title_idx`. ## Compound selectors in Prisma Client Prisma Client's single-row operations (`findUnique`, `findUniqueOrThrow`, `update`, `upsert`, `delete`) accept only a **unique where**: an object that names at least one unique criterion of the model. For a composite key that criterion is a nested object whose property name is generated from the schema: - The default name is the **field names joined by underscores**: `authorId_slug`, `title_locale`. Field names are used even when the columns are mapped to other names. - Passing the fields flat, as `{ authorId: 7, slug: "hello" }`, does not satisfy the type, because no single field is unique on its own. The same flat object is fine in `findFirst`, which takes any filter. - The `name:` argument replaces the generated name: with `@@id([authorId, slug], name: "postKey")` the call becomes `where: { postKey: { authorId: 7, slug: "hello" } }`. Writing the call that uses the selector is the client's subject; what matters here is that the schema decides the selector's existence and name. ## Naming in the database: `map:` `name:` and `map:` are easy to confuse: - `name:` (on `@@id` and `@@unique`) changes only the **Prisma Client** selector. - `map:` changes only the **database** name of the constraint or index, for example `@@index([published, title], map: "ix_post_feed")`. Use it to keep a legacy database's existing names, or to follow a naming rule. Without `map:`, Prisma builds names from the table and column names: `{table}_pkey`, `{table}_{columns}_key`, `{table}_{columns}_idx`. ## Options worth knowing on PostgreSQL 1. **Index access method.** `@@index([title], type: Hash)` produces `CREATE INDEX "Post_title_idx" ON "Post" USING HASH ("title")`. The accepted types are `BTree` (the default), `Hash`, `Gist`, `Gin`, `SpGist` and `Brin`; `Gin`, `Gist`, `SpGist` and `Brin` indexes can take an `ops:` operator class on the field. 2. **Sort order.** `@@index([createdAt(sort: Desc)])` declares a descending column in the index. 3. **Partial indexes.** A `where:` argument on `@@index` and `@@unique` exists, but it requires the `partialIndexes` preview feature in the generator block. 4. **What the schema cannot express.** Expression indexes (such as one on `lower(title)`) and `CREATE INDEX CONCURRENTLY` are not available in the schema language; they are added by editing a migration's SQL by hand. ## Rules that trip people up - A model may not have both `@id` and `@@id`; it has one primary key. - Fields in `@id` or `@@id` must be required. An optional field in a `@@unique` does not count as the model's identifying criterion, because `NULL`s are distinct; a model needs at least one unique criterion made only of required fields. - `@@index` never makes anything unique, and no compound selector appears for it, so `findUnique` cannot use it. Choosing whether a natural composite key or a surrogate id is the better design, and how the engine uses a multi-column index, are relational design topics; Prisma's part is how the choice is declared and what the client derives from it.
- In Prisma 7, what is the difference between the name: and map: arguments on @@unique?`name:` renames the compound selector Prisma Client exposes, for example `titleLocale` instead of `title_locale`; the database is untouched. `map:` sets the name of the unique index in the database and leaves the client API alone. Teams use `map:` to keep legacy constraint names and `name:` to give call sites a readable key.
- Why can't findUnique use the fields of a Prisma 7 @@index?`findUnique` only accepts a unique criterion, because it promises at most one row. An `@@index` is a plain lookup index with no uniqueness guarantee, so Prisma generates no selector for it. Query those columns with `findFirst` or `findMany`; the database can still use the index to serve the filter.
- @@index([a, b]) also makes the pair unique, so findUnique can use it.
- A composite key is passed flat to findUnique, as { authorId, slug }.
- The map: argument renames the selector that Prisma Client exposes.
- A model can declare an @id field and an @@id block together.
- Prisma's schema can declare expression indexes such as lower(title) directly.