Skip to content

Detect N+1 queries

An N+1 is flagged when the same query shape runs at least 5 times on the same connection within 1000 ms, with differing literal values. Both numbers can be changed in Settings.

All of these must hold:

  • The same shape.
  • On the same connection.
  • At least N+1 minimum repeats times (default 5, allowed 2 to 1000).
  • Within the N+1 window (default 1000 ms, allowed 10 to 60000). A gap longer than the window ends the run.
  • With differing literal values. Statements that still carry unbound placeholders such as $1 or ? count as differing.

Statements whose first keyword is begin, start, commit, end, rollback, savepoint, release, abort, set, show, reset, discard, deallocate, prepare, listen, unlisten or notify are never counted.

  • The identical statement with identical values, repeated.
  • Repeats spread over more than the window, or split across different connections.
  • Fewer repeats than the minimum.

A loop that loads one parent row, then one child query per row:

SELECT id, title FROM posts LIMIT 5;
SELECT * FROM comments WHERE post_id = 1;
SELECT * FROM comments WHERE post_id = 2;
SELECT * FROM comments WHERE post_id = 3;
SELECT * FROM comments WHERE post_id = 4;
SELECT * FROM comments WHERE post_id = 5;

Without detection you see six separate rows. With the defaults, the five comments queries share one shape (SELECT * FROM comments WHERE post_id = ?), run on one connection within the window, and differ in value. SQLEye collapses them into one expandable row marked ×5. Press Enter to expand it.

The usual fix is one query for all rows:

SELECT * FROM comments WHERE post_id IN (1, 2, 3, 4, 5);

That appears as a single event, and no group is created.

When a group is detected, the earlier events of the burst are re-sent tagged with the group, so the whole burst is collapsed, not only the events after the threshold. The Shapes tab shows the number in its N+1 hits column. Use N+1 only to list groups.

Open Settings (⌘, / Ctrl+,) and change N+1 minimum repeats or N+1 window. Raise the repeats if small legitimate loops are flagged; widen the window to catch slower loops. See the settings reference.

SQLEye is developed and maintained by CodeROG. This page is also available as Markdown.