N plus one queries
Local baseline: Node.js 22.16.0. Actual local SQLite 3.49.1 via experimental node:sqlite. No third-party packages or external connections.
Try the local 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();}Run node main.mjs in a disposable directory with the files shown. Expected standard output:
3 [[1,10],[2,20]]1 [[1,10],[2,20]]An experimental warning is expected on stderr for this local version.
How it works
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.
Common mistake
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.
Practice
Add an author with no books. Modify both approaches to produce identical parent records including an empty book list.
Documentation: primary source. Candidate lookup: node-n-plus-one-queries-lookup. Prerequisite: node-schema-migrations (platform route unverified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
N plus one queries — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
With 10 parents and one child query per parent, how many calls?
What can a LEFT JOIN preserve?
What was actually measured in the example?