Selecting and Including Data

1. Selecting Specific Fields

await prisma.user.findMany({ select: { id: true, email: true } });
TipDetail
Reduce I/OReflects in SELECT column list
TypeScript narrows resultOnly selected fields available
await prisma.user.findMany({ include: { posts: true, profile: true } });
PatternUse
include allinclude: { relation: true }
include with options{ relation: { where, orderBy, take } }

3. Understanding Select vs Include

select

  • Whitelist fields/relations
  • Result type narrowed
  • Smallest payload

include

  • Adds relations to default fields
  • Includes all scalar fields
  • Cannot mix with select at same level
ChooseWhen
selectNeed to trim scalars
includeKeep all scalars, add relations

4. Nesting Deep Selections

await prisma.user.findUnique({
  where: { id: 1 },
  select: { posts: { select: { comments: { select: { body: true } } } } }
});
AspectDetail
DepthUnlimited (watch N+1)
MixUse select + include at different levels

5. Using Relation Count

await prisma.user.findMany({
  select: { id: true, _count: { select: { posts: true, followers: true } } }
});
AspectDetail
Filter_count: { select: { posts: { where: {...} } } }

6. Selecting Nested Relations

PatternUse
Select + nested selectGranular projection
Include + nested selectAll scalars + selective children

7. Filtering Included Relations

await prisma.user.findMany({
  include: { posts: { where: { published: true } } }
});
UseDetail
Scoped relationsApply per-query filter
CombineWith take/orderBy

8. Limiting Included Records

OptionEffect
takePer-parent limit
skipOffset within relation
cursorCursor for paginated children

9. Ordering Included Relations

await prisma.user.findMany({
  include: { posts: { orderBy: { createdAt: "desc" }, take: 5 } }
});
PatternDetail
Single field{ field: "asc" }
Multi-fieldArray of orderBy objects

10. Using Distinct Selection

await prisma.order.findMany({ distinct: ["customerId"] });
AspectDetail
BehaviorReturns first row per distinct combination
CombineWith orderBy for deterministic results