MySQL, MariaDB and PostgreSQL

N+1 query detection

An N+1 shows up in the database as a query whose call count grows with the rows another query returns. dbtempo finds these queries without a repository; with one connected, it also names the code that sends them.

A worked example

A page lists fifty orders, then loads each order’s customer: one SELECT on orders, then SELECT * FROM customers WHERE id = ? fifty times. The customers query runs fifty times for every orders call. The fix is one query instead of fifty: a JOIN, or a single SELECT with WHERE id IN (…) for the fifty ids, which most ORMs call eager loading.

Finding it in your code

With a repository connected, dbtempo matches the child query to the SQL in your code, so the recommendation names the file that sends it. The loop itself usually sits where a relation is loaded lazily inside a loop; the fix is to load it up front.