findUnique
Find a single record by unique identifier (primary key or unique scalar)
Basic Usage
// By primary key
const user = await client.user.findUnique({
where: { id: "user_123" },
});
// By unique scalar
const user = await client.user.findUnique({
where: { email: "alice@example.com" },
});
Compound Keys
For models with compound unique constraints:
// Schema
const membership = s.model({
orgId: s.string(),
userId: s.string(),
role: s.string(),
}).id(["orgId", "userId"]);
// Query by compound key
const member = await client.membership.findUnique({
where: {
orgId_userId: {
orgId: "org_1",
userId: "user_1",
},
},
});
// With custom name
const membership = s.model({ ... })
.id(["orgId", "userId"], { name: "membership_pk" });
const member = await client.membership.findUnique({
where: {
membership_pk: {
orgId: "org_1",
userId: "user_1",
},
},
});
Options
await client.user.findUnique({
where: { ... }, // Required: unique identifier
select: { ... }, // Optional: fields to return
include: { ... }, // Optional: relations to include
});
select and include control the returned shape — see Selecting Fields.
findUniqueOrThrow
Throws if the record doesn’t exist:
const user = await client.user.findUniqueOrThrow({
where: { id: "user_123" },
});
// Type: User (never null)
// Throws: NotFoundError if not found
Return Type
const user = await client.user.findUnique({
where: { id: "user_123" },
});
// Type: User | null
// With select
const user = await client.user.findUnique({
where: { id: "user_123" },
select: { id: true, email: true },
});
// Type: { id: string; email: string } | null
Valid Unique Scalars
The where must name at least one unique discriminator — a scalar marked
unique, or a complete compound constraint:
const user = s.model({
id: s.string().id(), // ✅ Primary key
email: s.string().unique(), // ✅ Unique scalar
name: s.string(), // ❌ Not a discriminator on its own
});
// Valid
await client.user.findUnique({ where: { id: "..." } });
await client.user.findUnique({ where: { email: "..." } });
// Invalid - TypeScript error, and a ValidationError at runtime
await client.user.findUnique({ where: { name: "..." } });
Narrowing a Unique Lookup
Alongside the discriminator you may pass ordinary non-unique scalar filters
and AND / OR / NOT. The row must satisfy all of it:
// "the user with this id, but only if they're still active"
const user = await client.user.findUnique({
where: {
id: "user_123",
status: "active",
NOT: { deletedAt: { not: null } },
},
});
// null when the id exists but the filter excludes it
The discriminator is still required — the extra filters narrow a unique lookup,
they never replace it. A where with only filters is a ValidationError, not a
scan.
The same where shape is accepted by
update, delete and
upsert. What “excluded” means there is per operation:
| Operation | Unique key matches, filter excludes |
|---|---|
findUnique |
null |
findUniqueOrThrow |
NotFoundError |
update / delete |
NotFoundError, nothing written |
upsert |
the create branch runs — and then hits the unique key that is already taken, so a UniqueConstraintError surfaces |
Relation filters work here too, in the same position and with the same meaning
as in findMany:
// "the account with this id, but only if it still has a live login"
const account = await client.account.findUnique({
where: {
id: 1,
logins: { some: { status: "live" } },
manager: { is: { active: true } },
},
});
They narrow the row exactly as a scalar filter does — including on update,
delete and upsert, per the table above. Self-relations are covered: on MySQL,
where an UPDATE may not read the table it is mutating, the engine compiles the
subquery through a derived table so the answer is the same everywhere.
Batching concurrent calls
With findUniqueBatching: true, VibORM merges the findUnique and
findUniqueOrThrow calls issued in the same tick into one read, as Prisma’s
dataloader does. This is the GraphQL N+1 case, where each resolver looks up one
row:
const client = createClient({ schema, driver, findUniqueBatching: true });
// One statement: SELECT … WHERE "id" IN (…)
const authors = await Promise.all(
posts.map((post) =>
client.user.findUnique({ where: { id: post.authorId } })
)
);
Each caller still gets what its call would return on its own: its own row (a
separate object, also when two calls name the same key), null, or
NotFoundError. Extensions’ call parts, the cache, operation units
and permissions still see one operation per
call. Only the statement is shared.
Batching is off by default (it was on in 1.4.0). The merged read runs in the
async context of the batch’s first call, and the calls of one tick on one
client can come from different requests: a driver that picks its database or
its session settings from AsyncLocalStorage would read the first request’s
for all of them, and the statement is traced under the first request’s span.
Turn it on where every call of a client belongs to one request, or where
nothing below the client reads the caller’s async context.
Calls are merged only when all of these hold:
- They come from the same client view (the same
$extendsor$asresult) and run outside any transaction. Calls inside$transactionare never merged. - They read the same model with the same
select,includeandomit(nested arguments included) and the same extension arguments. - The
whereis the unique key alone: one field, or one complete compound key, whose fields arestring,intorbigIntscalars. Awherethat adds a filter, or a key of another type (dateTime,decimal,blob…), runs as its own statement. - No extension rewrites statements, and the driver installs no result parser of its own.
A few things change:
- One tick of waiting. Calls wait until the current synchronous code, and
the promise callbacks it queued, have run (
process.nextTick, or the end of the current synchronous run where there is noprocess). An isolated call pays about 2 µs for it on SQLite. - Some misses cost a second statement. If the merged read returns no row
for a string key, VibORM reads that key again on its own. A case-insensitive
or space-padding collation (MySQL’s default, PostgreSQL’s
citext) can match a row that JavaScript equality would not. AnintorbigIntkey that is not returned answersnulldirectly. A missingfindUniqueOrThrowkey is read again on its own, so itsNotFoundErroris the one it would throw alone. - Failures are retried one call at a time. If the merged read fails, each call runs on its own and gets its own result or error.
- Large batches are split to fit the driver’s bind-parameter limit (D1 allows 100 per statement). PostgreSQL binds a single-field key list as one array parameter.
- Tracing. Each call keeps its operation span. The merged statement appears under the first call’s span; the other calls’ operations have no statement span. When the merged read fails and every call recovers on its own, the failure is not logged as an error.
- Ordering. A
findUniqueyou do notawaitcan now run after a write you start later in the same tick, so it may see that write. If the read must not see the write,awaitthe read first.
With 50 concurrent calls by id, the batch sends 1 statement instead of 50. On
a simulated connection that waits 20 ms per statement and runs one statement
at a time (like pg over Hyperdrive), this takes 22 ms instead of 1,080 ms. On
in-memory PGlite it takes 0.6 ms instead of 7.8 ms.
To get-or-create a record atomically, use upsert instead of a findUnique + create pair.