Selecting and Including Data
1. Selecting Specific Fields
await prisma.user.findMany({ select: { id: true, email: true } });
| Tip | Detail |
| Reduce I/O | Reflects in SELECT column list |
| TypeScript narrows result | Only selected fields available |
await prisma.user.findMany({ include: { posts: true, profile: true } });
| Pattern | Use |
| include all | include: { 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
| Choose | When |
| select | Need to trim scalars |
| include | Keep all scalars, add relations |
4. Nesting Deep Selections
await prisma.user.findUnique({
where: { id: 1 },
select: { posts: { select: { comments: { select: { body: true } } } } }
});
| Aspect | Detail |
| Depth | Unlimited (watch N+1) |
| Mix | Use select + include at different levels |
5. Using Relation Count
await prisma.user.findMany({
select: { id: true, _count: { select: { posts: true, followers: true } } }
});
| Aspect | Detail |
| Filter | _count: { select: { posts: { where: {...} } } } |
6. Selecting Nested Relations
| Pattern | Use |
| Select + nested select | Granular projection |
| Include + nested select | All scalars + selective children |
7. Filtering Included Relations
await prisma.user.findMany({
include: { posts: { where: { published: true } } }
});
| Use | Detail |
| Scoped relations | Apply per-query filter |
| Combine | With take/orderBy |
8. Limiting Included Records
| Option | Effect |
take | Per-parent limit |
skip | Offset within relation |
cursor | Cursor for paginated children |
9. Ordering Included Relations
await prisma.user.findMany({
include: { posts: { orderBy: { createdAt: "desc" }, take: 5 } }
});
| Pattern | Detail |
| Single field | { field: "asc" } |
| Multi-field | Array of orderBy objects |
10. Using Distinct Selection
await prisma.order.findMany({ distinct: ["customerId"] });
| Aspect | Detail |
| Behavior | Returns first row per distinct combination |
| Combine | With orderBy for deterministic results |