Part 5: Advanced Querying, Aggregations, and Production Best Practices
Introduction
Advanced Filtering and Querying
Complex Nested Filters
// Find published posts by active authors who have verified emails
// and posts must have at least 2 approved comments with tags 'typescript' or 'database'
const posts = await prisma.post.findMany({
where: {
published: true,
author: {
isActive: true,
emailVerified: true,
role: {
in: ['ADMIN', 'EDITOR']
}
},
comments: {
some: {
approved: true,
content: {
contains: 'great',
mode: 'insensitive'
}
}
},
tags: {
some: {
slug: {
in: ['typescript', 'database']
}
}
},
viewCount: {
gte: 100
}
},
include: {
author: {
select: {
id: true,
name: true,
email: true
}
},
tags: true,
_count: {
select: {
comments: true
}
}
},
orderBy: [
{ viewCount: 'desc' },
{ createdAt: 'desc' }
]
});Using NOT, AND, OR
JSON Field Filtering (PostgreSQL)
Aggregations and Grouping
Count, Sum, Average, Min, Max
Group By
Monthly Statistics
Full-Text Search
PostgreSQL Full-Text Search
Advanced Full-Text Search with Raw SQL
Raw SQL Queries
When to Use Raw SQL
Typed Raw Queries
Safe Parameterization
Execute Raw (for non-SELECT queries)
Optimistic Concurrency Control
Soft Deletes
Connection Pooling and Performance
Database Connection Best Practices
Connection Pool Configuration
Query Optimization
Data Seeding
Middleware and Logging
Query Logging Middleware
Soft Delete Middleware
Production Deployment Checklist
1. Environment Variables
2. Migration Strategy
3. Health Check Endpoint
4. Error Monitoring
5. Backup Strategy
Conclusion
Resources
Last updated