Skip to main content

Handling Optional and Null Values

1. Using Optional Fields

SyntaxEffect
name String?Column nullable
TS typestring | null
Defaultnull if no value provided

2. Setting Null Values

await prisma.user.update({
  where: { id: 1 },
  data: { middleName: null }
});
Field TypeNull Constant
Scalarnull
JSONPrisma.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 } } });
FilterMeaning
{ 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";
OperatorFalls back when
??null or undefined
||Any falsy value (avoid for strings/numbers)

5. Understanding Undefined vs Null

ValueEffect on update
undefinedField skipped
nullSets column to NULL (requires optional)
Missing keySame as undefined

6. Setting Default Values

PatternExample
Schema default@default("draft")
Function default@default(now())
App fallbackdata.status ?? "draft"

7. Using Required Fields

AspectDetail
DefinitionField without ?
ValidationTS create input requires value (or default)
ErrorMissing required → P2012

8. Checking Field Existence

StrategyExample
Truthyif (user.email) ...
Type guardif (user.email !== null) ...
Optional chaininguser.profile?.bio

9. Updating Fields to Null

ConstraintDetail
Field optionalRequired to accept null
JSON nullUse Prisma.JsonNull

10. Validating Nullable Fields

ToolHelper
Zodz.string().nullable()
TypeScriptEnable strictNullChecks
RuntimeThrow if business rule forbids null

Was this article helpful?