N+1 query detection
An N+1 pattern occurs when an initial query returns N items and application code makes an additional query for each item. It can multiply round trips even when each query is individually simple. Count actual issued statements in a controlled workload. The fixture reads authors and then fetches each author’s books, making three calls for two authors. A LEFT JOIN returns the same author/book pairs in one statement, including authors without books when grouped correctly by the application. In other cases use a bounded batch of IDs or a suitable relation-loading strategy. Joins can duplicate parent fields; paging parents requires care. Compare query plans, returned row counts and data sizes, not only call counts. This measures SQLite statement calls, not network latency or ORM speed. Do not assert that a join is always faster or that eager loading always makes exactly one SQL statement. Inspect the actual generated query strategy. Evidence: Actual local SQLite 3.49.1 via experimental node:sqlite. Source: https://orm.drizzle.team/docs/select
Formal Syntax & Structure
See example for the scoped contractWorking Example
import {DatabaseSync} from 'node:sqlite';const db=new DatabaseSync(':memory:');try { db.exec("CREATE TABLE author(id INTEGER PRIMARY KEY); CREATE TABLE book(id INTEGER PRIMARY KEY, author_id INTEGER); INSERT INTO author VALUES(1),(2); INSERT INTO book VALUES(10,1),(20,2)"); let calls=0; function all(sql,...args){calls++;return db.prepare(sql).all(...args);} const pairs=all('SELECT id FROM author ORDER BY id').flatMap(a=>all('SELECT id FROM book WHERE author_id=? ORDER BY id',a.id).map(b=>[a.id,b.id])); console.log(calls,JSON.stringify(pairs)); calls=0; const joined=all('SELECT a.id AS aid,b.id AS bid FROM author a LEFT JOIN book b ON b.author_id=a.id ORDER BY a.id,b.id').map(r=>[r.aid,r.bid]); console.log(calls,JSON.stringify(joined));}finally{db.close();}