Dev.to
7/20/2026

Killing N+1 Queries: From Per-Row Lookups to Flat, Batched Reads
Short summary
A practical walkthrough of fixing N+1 queries in two forms: the classic per-row lookup inside a loop, and a sneakier nested variant hidden inside helper functions. The solution is to gather all needed IDs upfront, de-duplicate, and run a fixed number of set-based IN queries, then assemble the object graph from in-memory maps. The post includes Kotlin/Exposed code examples and discusses writing tests to prevent regressions.
- •Classic N+1: per-row DB lookups inside a loop cause thousands of queries
- •Hidden N+1: helper functions like isPremium() can nest fan-outs invisibly
- •Fix: batch all reads into set-based IN queries, build objects from in-memory maps
Generated with AI, which can make mistakes.
Is this a good recommendation for you?



