Handling Optional and Null Values
1. Using Optional Fields
| Syntax | Effect |
name String? | Column nullable |
| TS type | string | null |
| Default | null if no value provided |
2. Setting Null Values
await prisma.user.update({
where: { id: 1 },
data: { middleName: null }
});
| Field Type | Null Constant |
| Scalar | null |
| JSON | Prisma.JsonNull (JSON null) or Prisma.DbNull (SQL NULL) |
3. Filtering Null Fields
await prisma.user.findMany({ where: { deletedAt: null } });
await prisma.user.findMany({ where: { deletedAt: { not: null } } });
| Filter | Meaning |
{ field: null } | IS NULL |
{ field: { not: null } } | IS NOT NULL |
{ field: { equals: null } } | Explicit IS NULL |
4. Using Nullish Coalescing
const displayName = user.name ?? "Anonymous";
| Operator | Falls back when |
?? | null or undefined |
|| | Any falsy value (avoid for strings/numbers) |
5. Understanding Undefined vs Null
| Value | Effect on update |
undefined | Field skipped |
null | Sets column to NULL (requires optional) |
| Missing key | Same as undefined |
6. Setting Default Values
| Pattern | Example |
| Schema default | @default("draft") |
| Function default | @default(now()) |
| App fallback | data.status ?? "draft" |
7. Using Required Fields
| Aspect | Detail |
| Definition | Field without ? |
| Validation | TS create input requires value (or default) |
| Error | Missing required → P2012 |
8. Checking Field Existence
| Strategy | Example |
| Truthy | if (user.email) ... |
| Type guard | if (user.email !== null) ... |
| Optional chaining | user.profile?.bio |
9. Updating Fields to Null
| Constraint | Detail |
| Field optional | Required to accept null |
| JSON null | Use Prisma.JsonNull |
10. Validating Nullable Fields
| Tool | Helper |
| Zod | z.string().nullable() |
| TypeScript | Enable strictNullChecks |
| Runtime | Throw if business rule forbids null |