الانتقال إلى المحتوى
قواعد البياناتQuery Tuning· 6 دقائق للقراءة

Every Query Is Fast but the Page Is Slow: Spotting N+1 from the Database Side

N+1 never shows up as a slow query. It shows up as a cheap one that runs thousands of times, and you find it by sorting on executions, not on average duration.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

The orders page feels sluggish, so someone opens and sorts by average duration. The slowest statement on that page averages 0.18 ms; the others, 0.02 to 0.05 ms. The verdict: "the database is fine, it must be the app." In a test that reproduces the page against SQL Server 2022 in a local Docker container (50 orders, then their lines and their customers), the page took a median of 72 to 75 ms across three runs of 50 page loads. Query Store recorded about 3.5 ms of execution per page. Both numbers are right; the gap between them is the bug.

The common misconception

The belief: if every query a request runs is fast, the database can't be why the request is slow.

It's how database tuning is usually taught: find the slowest query, read its plan, fix it. The tools follow the same idea. PostgreSQL's log_min_duration_statement logs only statements that ran at least as long as the threshold, so a 0.05 ms query never appears. A list sorted by average duration puts the heaviest single statement on top. And each of those views is honest; it just answers a different question from "why is this page slow?".

What actually happens

Each statement is a round trip

For every query, the application sends the statement, the server runs it and sends rows back, and the application reads them before it sends the next one. The server measures the middle part, per statement. The time spent travelling between application and database, and the gaps between statements, belong to no query at all, so no per-query statistic can show them.

The test page ran 101 statements: one for the orders, then one for each order's lines and one for each order's customer. Per page, the server executed about 3.5 ms in total; the client waited about 73 ms. The rest, roughly 0.7 ms per statement on this setup, was round trips. That per-trip cost depends on your network and driver, but it's always paid N times, and N grows with the page size.

What the database actually records

The application sent each statement with a parameter, so the database saw one statement text executed many times, not 2,500 different queries. Query Store aggregated it into one entry: 2,500 executions of the lines query, averaging 43 to 48 µs, returning 3 rows each. PostgreSQL's pg_stat_statements does the same by design: queries that differ only in their constants are combined into a single entry, with the constants shown as $1, and its calls column counts the executions.

The fingerprint is in the counts

An N+1 leaves a pattern that's easy to read once you look for it. In the test, the orders query ran 50 times and the lines and customer queries ran 2,500 times each: exactly 50 per execution of the parent, the page size. Each child returned 1 to 3 rows per call. A cheap statement with a high count, few rows per call, and a count that's a clean multiple of another statement's count is a loop in the application, seen from the database.

Averages hide it, and fixing it makes the average look worse

The same page written as one join told the opposite story:

50 page loads, testedN+1 (101 statements)One join (1 statement)
Client wait per page (median, 3 runs)72 to 75 ms1.6 to 2.2 ms
Server execution per page (Query Store)about 3.5 msabout 1.0 to 1.2 ms
Slowest statement's average duration0.18 ms1.0 to 1.2 ms

The fix made the page about 40 times faster, and it also made the "slowest query" five to six times slower, because one statement now does the work of 101. A team that judges the database by its slowest average would call the fix a regression.

Look at counts, not averages

SQL
-- "Which query is slow?" sorted by average durationSELECT TOP (10) qt.query_sql_text,       rs.avg_duration / 1000.0 AS avg_msFROM sys.query_store_runtime_stats AS rsJOIN sys.query_store_plan AS p ON p.plan_id = rs.plan_idJOIN sys.query_store_query AS q ON q.query_id = p.query_idJOIN sys.query_store_query_text AS qt  ON qt.query_text_id = q.query_text_idORDER BY rs.avg_duration DESC;-- Tested: the N+1 statements (0.02-0.05 ms) rank last

On PostgreSQL, pg_stat_statements gives the same view. It needs shared_preload_libraries = 'pg_stat_statements' and CREATE EXTENSION pg_stat_statements; the columns below are from the PostgreSQL 18 docs, and the query wasn't run for this article:

SQL
SELECT calls, round(total_exec_time) AS total_ms,       round(mean_exec_time::numeric, 3) AS mean_ms,       rows / NULLIF(calls, 0) AS rows_per_call, queryFROM pg_stat_statementsORDER BY calls DESCLIMIT 10;

How to apply it in your project

  1. Sort by executions and total timeMake the weekly check in Query Store or pg_stat_statements sort by execution count and total duration. Look for statements with tiny averages near the top.
  2. Match the countsFor each suspect, find the statement whose count divides it cleanly, and check the rows per call. That pair is the loop and its parent.
  3. Fix it in the applicationReplace the loop with a join or a projection, or batch the ids into one query. For EF Core, the .NET path's article "Beyond Include: Fixing N+1 in EF Core With Projections and Split Queries" covers the code side.
  4. Verify with both numbersAfter the fix, the statement count per request should drop and the client-side latency should follow, even if the slowest average goes up.

Key takeaways

  • A fast query can still make a slow page: the cost of N+1 is round trips, which no per-query statistic includes.
  • In the test, the page waited about 73 ms while the server executed about 3.5 ms of it.
  • The database records an N+1 as one parameterized statement with a huge count and few rows per call, often an exact multiple of another statement's count.
  • Sort by executions and total time; sorting by average duration ranks N+1 last and makes the fix look like a regression.
  • If values are typed into the SQL text, group SQL Server's statistics by query_hash.

📚 المصادر

  1. pg_stat_statements — PostgreSQL Documentation
  2. Monitor Performance by Using the Query Store — SQL Server, Microsoft Learn
  3. sys.dm_exec_query_stats — SQL Server, Microsoft Learn
  4. sys.query_store_runtime_stats — SQL Server, Microsoft Learn
  5. Error Reporting and Logging: log_min_duration_statement — PostgreSQL Documentation

التعليقات (0)