What is N+1 Query Problem?
Fetching a list with one query then one extra query per row for its relations — 1 plus N round trips. ORMs make it easy to write; batching, joins, or dataloaders collapse it to a constant handful.
Example
A project list page queries every project, then fires one follow-up query per project for owner profiles; a single join through Drizzle relations returns the same page in two round trips.
What people get wrong
Trusting tiny seed data to reveal query shape. Small tables hide N+1 while production-sized lists expose it, so test pagination with realistic volumes.
Frequently asked questions
How do I spot an N+1 query?
Watch request logs for repeated identical queries differing only by id. One list fetch followed by dozens of single-row lookups is the signature pattern.
Do joins always fix N+1?
Not always, but batching does: joins, grouped IN queries, or dataloader batching all collapse N round trips into a constant few. Measure before and after.
Related terms
EXPLAIN Query Plan
The command prefix showing how the database will execute a query: scan types, index usage, join order, and row estimates. Reading plans separates “add an index” guesses from evidence about what the planner actually does.
Drizzle ORM
A typed TypeScript layer over SQL for schema definition and queries. Types generated from the live schema keep app code and database in agreement.
Connection Pooling
Reusing a small set of open database connections across many requests instead of dialing fresh each time. Pools cap concurrency, cut handshake latency, and keep serverless bursts from overwhelming Postgres.
B-Tree Index
The default balanced-tree structure making equality and range lookups fast without scanning every row. Add one where queries filter, join, or sort — then confirm with EXPLAIN before assuming victory.
Composite Index
One index spanning several columns for queries that always filter them together, ordered most-selective first. A three-column composite beats three single-column indexes on the same query shape.
Partial Index
An index covering only rows matching a predicate, such as live subscriptions where status is active. Smaller, faster, and cheaper to maintain than indexing rows queries never touch.