{"id":"sql-performance/blocking-deadlocks","corpus":"sql-performance","engine":null,"language":"en","title":"Blocking and deadlocks","description":"Find which sessions block which with each engine's lock views, read the deadlock graph, then fix it with shorter transactions, indexes and consistent order.","body":{"slug":"blocking-deadlocks","engines":["SQL Server","PostgreSQL","MySQL","Oracle"],"symptoms":["Blocking and deadlocks","Sudden slowdown"],"h1":"Blocking and deadlocks","lede":"Sessions queue up or kill each other with deadlock errors. How to see the wait chain on SQL Server, PostgreSQL, MySQL and Oracle, read the deadlock graph, and fix the design that causes it.","symptom_html":"<p>Queries hang for seconds or fail with deadlock errors. Locking is normal - the problems are <em>blocking that lasts</em> (a reader or writer stuck behind a transaction the app forgot to commit) and <em>deadlocks</em> (two sessions each holding what the other needs). Both are found the same way: by asking the engine who is waiting on whom.</p>","diagnosis_html":"<h3>Catch the wait chain live</h3>\n<p>Ask the engine who is waiting on whom. The query differs; the shape of the answer does not.</p>\n<h3>SQL Server: the wait chain</h3>\n<p>Who is blocked by whom, and what they are running:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT r.session_id, r.blocking_session_id, r.wait_type, r.wait_time,\nr.wait_resource, LEFT(t.text, 100) AS sql_text\nFROM sys.dm_exec_requests AS r\nCROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS t\nWHERE r.blocking_session_id &lt;&gt; 0;</code></pre>\n<h3>PostgreSQL: pg_blocking_pids</h3>\n<p>It builds the chain for you:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SELECT blocked.pid AS blocked_pid, LEFT(blocked.query, 60) AS blocked_query,\nblocking.pid AS blocking_pid, LEFT(blocking.query, 60) AS blocking_query,\nblocking.state AS blocking_state\nFROM pg_stat_activity AS blocked\nJOIN pg_stat_activity AS blocking\nON blocking.pid = ANY (pg_blocking_pids(blocked.pid));</code></pre>\n<p>The blocking session's <code>query</code> is whatever it ran last, which is often not the statement that took the lock: a session showing <code>idle in transaction</code> with a harmless SELECT is still holding the locks of an earlier UPDATE in the same transaction.</p>\n<h3>MySQL: sys.innodb_lock_waits</h3>\n<p>The sys schema resolves InnoDB lock waits and even generates the kill statements. <code>sql_kill_blocking_query</code> only stops the blocker's current statement; if it is idle inside an open transaction, only <code>sql_kill_blocking_connection</code> releases the locks (by rolling the transaction back):</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>SELECT * FROM sys.innodb_lock_waits;</code></pre>\n<h3>Oracle: v$session.blocking_session</h3>\n<p>The blocking session is a column:</p>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>SELECT sid, serial#, username, event, blocking_session, sql_id\nFROM v$session\nWHERE blocking_session IS NOT NULL;</code></pre>\n<p>In every engine the fix starts with the <em>head</em> of the chain - the session holding the lock - and the question is always the same: why does it hold the lock, and what is it waiting for? (An idle-in-transaction session on PostgreSQL, an uncommitted transaction someone's management tool left open, a long-running batch.)</p>\n<h3>Read the deadlock graph</h3>\n<p>A deadlock error means the engine chose a victim; the graph shows both queries and both locks. SQL Server keeps every deadlock in the <code>system_health</code> event session:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT x.event_xml.value('(event/@timestamp)[1]', 'datetime2(3)') AS deadlock_time_utc,\nx.event_xml.query('(event/data[@name=\"xml_report\"]/value/deadlock)[1]') AS deadlock_graph\nFROM sys.fn_xe_file_target_read_file(N'system_health*.xel', NULL, NULL, NULL) AS f\nCROSS APPLY (SELECT CAST(f.event_data AS XML) AS event_xml) AS x\nWHERE f.object_name = N'xml_deadlock_report'\nORDER BY deadlock_time_utc DESC;</code></pre>\n<p>This reads the session's event files, which hold far more history than its small in-memory ring buffer. The XML methods need <code>SET QUOTED_IDENTIFIER ON</code> (SSMS has it on; plain <code>sqlcmd</code> does not). Save a <code>deadlock_graph</code> value as an <code>.xdl</code> file and SSMS draws it.</p>\n<p>On MySQL, <code>SHOW ENGINE INNODB STATUS</code> prints the latest deadlock under LATEST DETECTED DEADLOCK, and <code>innodb_print_all_deadlocks = ON</code> logs every one. On PostgreSQL, every deadlock is written to the server log as an ERROR naming both processes and their statements; turn on <code>log_lock_waits</code> (off by default) to also log any lock wait longer than <code>deadlock_timeout</code>, one second by default. Oracle raises ORA-00060 in the victim session and writes the deadlock graph to a trace file named in the alert log. The two statements in a graph usually arrive as one long line each - run them through the <a href=\"/tools/sql-formatter\">SQL formatter</a> to see what each transaction touched, in which order.</p>","fix_html":"<p>The graph's two statements tell you the pattern, and the fixes are nearly universal:</p>\n<p><strong>Shorten the transactions that hold locks.</strong> The head of the chain usually holds locks across work it should not: an application call, an HTTP request, or user think time inside a transaction. Commit as soon as the write is done - lock duration is the whole problem.</p>\n<p><strong>Index what the locks touch.</strong> On InnoDB, an UPDATE or DELETE (or SELECT ... FOR UPDATE) that finds its rows by scanning locks every row it reads, plus the gaps between them under the default REPEATABLE READ. On SQL Server a scanning writer takes update locks row by row and has to wait at every row another session holds. An index on the predicate shrinks that to the rows actually changed, and the contention often disappears with no other change. PostgreSQL only locks the rows it modifies, so this one matters less there. The index for a writer that reaches its orders by customer, on each engine:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX idx_orders_customer\nON dbo.Orders (CustomerId);</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX CONCURRENTLY idx_orders_customer\nON orders (customer_id);</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>ALTER TABLE orders\nADD INDEX idx_orders_customer (customer_id);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>CREATE INDEX idx_orders_customer\nON orders (customer_id);</code></pre>\n<p><strong>Touch objects in the same order everywhere.</strong> Most deadlocks are two code paths updating tables A then B, and B then A. Pick one order and enforce it in both.</p>\n<p><strong>Let readers stop blocking writers where the engine allows it.</strong> PostgreSQL's MVCC means plain reads never block writes. Blocking there is writer against writer, or DDL: an <code>ALTER TABLE</code> needs an ACCESS EXCLUSIVE lock, waits behind any long-running SELECT on the table, and every new query on that table then queues behind the ALTER. Run migrations with <code>SET lock_timeout = '5s'</code> so they give up instead of stalling the application. On SQL Server, <code>ALTER DATABASE [MyDb] SET READ_COMMITTED_SNAPSHOT ON</code> (RCSI, the default in Azure SQL Database) gives readers the last committed version of each row from tempdb's version store instead of taking shared locks. On MySQL, InnoDB plain SELECTs are already non-locking consistent reads; only <code>FOR UPDATE</code>, <code>FOR SHARE</code> and the reads inside INSERT ... SELECT take locks. The two settings:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>ALTER DATABASE [MyDb] SET READ_COMMITTED_SNAPSHOT ON;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SET lock_timeout = '5s';</code></pre>\n<p>RCSI needs tempdb room for the version store and a moment of exclusive access to switch on, so make the change in a maintenance window, not mid-incident. <code>lock_timeout</code> applies per session, so set it in the migration script itself.</p>\n<p><strong>Retry deadlocks, do not prevent them all.</strong> A deadlock victim should retry; the engine resolved an impossible wait. If a deadlock happens daily between the same statements, fix the pattern - if it happens weekly between different ones, retry logic is the correct design.</p>\n<h3>When the locks are the design</h3>\n<p>Blocking that stays inside a nightly batch window, where the queue drains on schedule, is often exactly what the batch schedule implies - measure whether anyone is actually hurt before re-engineering it. A first deadlock between two statements that have never met needs retry logic and a note, not a redesign. Do not reach for the kill button reflexively either: killing the head of the chain rolls its transaction back, and on a long batch that can take longer than the wait and redo its work. Read what the blocker is running first.</p>","checklist_html":["Catch the blocking live: run the engine's wait-chain query above and find the head.","Look at what the head-of-chain session is doing and whether it should still be in a transaction.","For deadlocks, get the graph (system_health event file / SHOW ENGINE INNODB STATUS / server log / Oracle trace file) and identify both statements.","Check both statements for missing indexes that make them lock more rows than they touch.","Shorten the offending transactions: no external calls or waits inside them.","Enforce one table access order across code paths that touch the same tables.","Add retry-on-deadlock to the call sites that can safely retry.","Re-run the wait-chain query at peak: the chain should be gone or trivially short."],"faqs":[{"question":"What is the difference between blocking and a deadlock?","answer":"Blocking is a queue: one session holds a lock, others wait, and they all get through once it commits. A deadlock is a cycle: two sessions each hold a lock the other needs, neither can proceed, and the engine kills one so the other can finish. Blocking is fixed by shortening or indexing; deadlocks additionally need consistent ordering and retry logic."},{"question":"Why is an idle session blocking everyone?","answer":"Almost always a transaction someone left open: a management tool tab with an uncommitted edit, an application bug that opens a transaction and throws before committing (idle in transaction on PostgreSQL), or a long batch's open transaction between statements. The wait-chain query identifies the session; the fix is closing it and fixing the code that left it open."},{"question":"Do indexes really fix lock contention?","answer":"When the contending statement reaches its rows by scan, yes: it takes locks on every row it reads past, not just the rows it matches. An index that turns the scan into a seek cuts the locked row count by orders of magnitude, which is why contention sometimes appears after data growth with no code change - see the bad index usage guide."},{"question":"Should I use NOLOCK or READ UNCOMMITTED to stop blocking?","answer":"It trades correctness for latency: dirty reads can return rows that were never committed, and scans running during page splits can skip rows or read the same row twice. Read-committed-snapshot gives readers a consistent committed version instead, which is the change to make when reporting queries block on OLTP writes on SQL Server."},{"question":"A deadlock happened once. Should I fix anything?","answer":"One deadlock between different statements a year is noise - add retry logic and move on. The graph is worth reading anyway: if both statements are hot application paths, the same cycle will repeat under load. SQL Server's system_health session, InnoDB status and the Postgres log all keep the evidence for you."}],"plan_group":null,"related_slugs":[]},"source_url":"https://sqlly.app/sql-performance/blocking-deadlocks","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/correlated-subquery","corpus":"sql-performance","engine":null,"language":"en","title":"Correlated subqueries and NOT IN","description":"A dependent subquery is executed again for every outer row. How to see the repeat count in a plan, index or rewrite it, and why NOT IN with NULLs is a trap.","body":{"slug":"correlated-subquery","engines":["PostgreSQL","MySQL","SQLite","Oracle","SQL Server"],"symptoms":["Slow query","High CPU"],"h1":"Correlated subqueries and NOT IN","lede":"A subquery that refers to the outer query can be executed once for every outer row. How each engine shows that in a plan, how to index or rewrite it, and why NOT IN over a nullable column is both slow and wrong.","symptom_html":"<p>A correlated subquery uses a value from the outer query, so in principle it has to be evaluated again for each outer row. Optimizers turn many of them into joins. When they cannot, the plan shows the subquery as a separate block that runs in a loop: <code>SubPlan</code> in PostgreSQL, <code>DEPENDENT SUBQUERY</code> in MySQL, <code>CORRELATED SCALAR SUBQUERY</code> in SQLite. The cost is the cost of one execution times the number of outer rows, which is easy to miss because the plan prints the subquery only once.</p>\n<p>The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> flags subqueries that are executed per row. The examples use a shop schema with 20,000 customers and 400,000 orders, with no index on <code>orders.customer_id</code> to begin with.</p>","diagnosis_html":"<h3>A subquery that runs once per outer row</h3>\n<p>This query counts the orders of 50 customers with a subquery in the select list:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT c.customer_id, c.email,\n       (SELECT count(*) FROM orders AS o WHERE o.customer_id = c.customer_id) AS order_count\nFROM customers AS c\nWHERE c.customer_id BETWEEN 100 AND 149;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Index Scan using customers_pkey on customers c  (cost=0.29..474112.66 rows=50 width=33) (actual rows=50.00 loops=1)\n  Index Cond: ((customer_id &gt;= 100) AND (customer_id &lt;= 149))\n  SubPlan 1\n    -&gt;  Aggregate  (cost=9482.06..9482.07 rows=1 width=8) (actual rows=1.00 loops=50)\n          -&gt;  Seq Scan on orders o  (cost=0.00..9482.00 rows=23 width=0) (actual rows=18.00 loops=50)\n                Filter: (customer_id = c.customer_id)\n                Rows Removed by Filter: 399982</code></pre>\n<p><code>loops=50</code> on the nodes under <code>SubPlan 1</code> is the repeat count, and the row counts next to it are per loop. Each loop scans all 400,000 orders, so the query reads 20 million rows to return 50.</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN SELECT c.customer_id, c.email,\n       (SELECT count(*) FROM orders AS o WHERE o.customer_id = c.customer_id) AS order_count\nFROM customers AS c\nWHERE c.customer_id BETWEEN 100 AND 149\\G</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>select_type: PRIMARY\n      table: c\n       type: range\n        key: PRIMARY\n       rows: 50\n      Extra: Using where\nselect_type: DEPENDENT SUBQUERY\n      table: o\n       type: ALL\n        key: NULL\n       rows: 398641\n      Extra: Using where</code></pre>\n<p>In MySQL, <code>DEPENDENT SUBQUERY</code> with <code>type: ALL</code> is the same thing: a full scan of <code>orders</code> for each of the 50 customers. A plain <code>SUBQUERY</code> without the word dependent runs once and is not a concern.</p>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>EXPLAIN QUERY PLAN\nSELECT c.customer_id, c.email,\n       (SELECT count(*) FROM orders AS o WHERE o.customer_id = c.customer_id) AS order_count\nFROM customers AS c\nWHERE c.customer_id BETWEEN 100 AND 149;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\" data-role=\"output\"><code>|--SEARCH c USING INTEGER PRIMARY KEY (rowid&gt;? AND rowid&lt;?)\n`--CORRELATED SCALAR SUBQUERY 1\n   `--SCAN o</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>EXPLAIN PLAN FOR\nSELECT c.customer_id, c.email,\n       (SELECT count(*) FROM orders o WHERE o.customer_id = c.customer_id) AS order_count\nFROM customers c\nWHERE c.customer_id BETWEEN 100 AND 149;\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation                           | Name        | Rows  | Bytes | Cost (%CPU)| Time     |\n|   0 | SELECT STATEMENT                    |             |    51 |  1377 | 16897   (1)| 00:00:01 |\n|   1 |  SORT AGGREGATE                     |             |     1 |     5 |            |          |\n|*  2 |   TABLE ACCESS FULL                 | ORDERS      |    22 |   110 |   650   (1)| 00:00:01 |\n|   3 |  TABLE ACCESS BY INDEX ROWID BATCHED| CUSTOMERS   |    51 |  1377 |     3   (0)| 00:00:01 |\n|*  4 |   INDEX RANGE SCAN                  | SYS_C008720 |    51 |       |     2   (0)| 00:00:01 |\n   2 - filter(\"O\".\"CUSTOMER_ID\"=:B1)</code></pre>\n<p>Oracle lists the subquery first, above the main query, and its filter compares the column with a bind placeholder, <code>:B1</code>, that is filled in for each outer row.</p>\n<p>SQL Server rewrites this query into an outer join by itself and reads <code>Orders</code> once:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS IO ON;\nGO\nSELECT c.CustomerId, c.Email,\n       (SELECT COUNT(*) FROM dbo.Orders AS o WHERE o.CustomerId = c.CustomerId) AS OrderCount\nFROM dbo.Customers AS c\nWHERE c.CustomerId BETWEEN 100 AND 149;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 2579, physical reads 0\nTable 'Customers'. Scan count 1, logical reads 2, physical reads 0</code></pre>\n<h3>NOT IN over a column that allows NULL</h3>\n<p><code>NOT IN</code> has to answer \"unknown\" when the subquery returns a NULL, so engines cannot treat it as a plain anti join unless the column is declared <code>NOT NULL</code>. To show it, add a table of referrals where <code>referred_by</code> is NULL for one customer in ten, then look for customers who never referred anyone:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE TABLE referrals (customer_id int NOT NULL, referred_by int);\n\nINSERT INTO referrals\nSELECT g, CASE WHEN g % 10 = 0 THEN NULL ELSE g / 2 + 1 END\nFROM generate_series(1, 20000) AS g;\n\nANALYZE referrals;\n\nEXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT c.customer_id\nFROM customers AS c\nWHERE c.customer_id NOT IN (SELECT r.referred_by FROM referrals AS r);</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Seq Scan on customers c  (cost=339.00..756.00 rows=10000 width=4) (actual rows=0.00 loops=1)\n  Filter: (NOT (ANY (customer_id = (hashed SubPlan 1).col1)))\n  Rows Removed by Filter: 20000\n  SubPlan 1\n    -&gt;  Seq Scan on referrals r  (cost=0.00..289.00 rows=20000 width=4) (actual rows=20000.00 loops=1)</code></pre>\n<p>Two things are wrong. PostgreSQL does not plan <code>NOT IN</code> as a join: it evaluates a <code>SubPlan</code> as a filter, hashed if the subquery result fits in <code>work_mem</code> and rescanned for every outer row if it does not. And the query returns <code>rows=0</code>. Because the subquery result contains NULLs, no customer can be proven to be absent from it, so <code>NOT IN</code> returns nothing at all.</p>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>CREATE TABLE referrals (customer_id NUMBER NOT NULL, referred_by NUMBER);\n\nINSERT INTO referrals\nSELECT customer_id,\n       CASE WHEN MOD(customer_id, 10) = 0 THEN NULL ELSE TRUNC(customer_id / 2) + 1 END\nFROM customers;\n\nCOMMIT;\n\nEXEC DBMS_STATS.GATHER_TABLE_STATS(USER, 'REFERRALS');\n\nEXPLAIN PLAN FOR\nSELECT c.customer_id\nFROM customers c\nWHERE c.customer_id NOT IN (SELECT r.referred_by FROM referrals r);\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation               | Name        | Rows  | Bytes | Cost (%CPU)| Time     |\n|   0 | SELECT STATEMENT        |             | 10001 | 90009 |    28   (0)| 00:00:01 |\n|*  1 |  HASH JOIN RIGHT ANTI NA|             | 10001 | 90009 |    28   (0)| 00:00:01 |\n|   2 |   TABLE ACCESS FULL     | REFERRALS   | 20000 | 80000 |    13   (0)| 00:00:01 |\n|   3 |   INDEX FAST FULL SCAN  | SYS_C008720 | 20000 |    97K|    15   (0)| 00:00:01 |</code></pre>\n<p>Oracle marks the null-aware version of the join with <code>NA</code>. SQL Server adds a second anti join to the plan whose only job is to look for a NULL in the subquery column.</p>","fix_html":"<h3>Rewrite the subquery as a join</h3>\n<p>A join with <code>GROUP BY</code> lets the engine read the inner table once, whatever the number of outer rows:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT c.customer_id, c.email, count(o.order_id) AS order_count\nFROM customers AS c\nLEFT JOIN orders AS o ON o.customer_id = c.customer_id\nWHERE c.customer_id BETWEEN 100 AND 149\nGROUP BY c.customer_id, c.email;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>GroupAggregate  (cost=9591.96..9599.96 rows=50 width=33) (actual rows=50.00 loops=1)\n  Group Key: c.customer_id\n  -&gt;  Sort  (cost=9591.96..9594.46 rows=1000 width=29) (actual rows=905.00 loops=1)\n        Sort Key: c.customer_id\n        Sort Method: quicksort  Memory: 67kB\n        -&gt;  Hash Right Join  (cost=9.91..9542.14 rows=1000 width=29) (actual rows=905.00 loops=1)\n              Hash Cond: (o.customer_id = c.customer_id)\n              -&gt;  Seq Scan on orders o  (cost=0.00..8482.00 rows=400000 width=8) (actual rows=400000.00 loops=1)\n              -&gt;  Hash  (cost=9.29..9.29 rows=50 width=25) (actual rows=50.00 loops=1)\n                    Buckets: 1024  Batches: 1  Memory Usage: 11kB\n                    -&gt;  Index Scan using customers_pkey on customers c  (cost=0.29..9.29 rows=50 width=25) (actual rows=50.00 loops=1)\n                          Index Cond: ((customer_id &gt;= 100) AND (customer_id &lt;= 149))\n                          Index Searches: 1</code></pre>\n<p>Use <code>LEFT JOIN</code> and count a column of the joined table so that customers with no orders still appear with a count of 0, as they did with the subquery. This is the better fix when the outer query returns many rows.</p>\n<h3>Index the correlated column</h3>\n<p>When the outer query returns few rows, running the subquery per row is fine as long as each run is an index lookup:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nEXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT c.customer_id, c.email,\n       (SELECT count(*) FROM orders AS o WHERE o.customer_id = c.customer_id) AS order_count\nFROM customers AS c\nWHERE c.customer_id BETWEEN 100 AND 149;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>SubPlan 1\n  -&gt;  Aggregate  (cost=4.88..4.89 rows=1 width=8) (actual rows=1.00 loops=50)\n        -&gt;  Index Only Scan using orders_customer_idx on orders o  (cost=0.42..4.83 rows=23 width=0) (actual rows=18.00 loops=50)\n              Index Cond: (customer_id = c.customer_id)</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nEXPLAIN SELECT c.customer_id, c.email,\n       (SELECT count(*) FROM orders AS o WHERE o.customer_id = c.customer_id) AS order_count\nFROM customers AS c\nWHERE c.customer_id BETWEEN 100 AND 149\\G</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>select_type: PRIMARY\n      table: c\n       type: range\n        key: PRIMARY\n       rows: 50\n      Extra: Using where\nselect_type: DEPENDENT SUBQUERY\n      table: o\n       type: ref\n        key: orders_customer_idx\n       rows: 22\n      Extra: Using index</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nEXPLAIN QUERY PLAN\nSELECT c.customer_id, c.email,\n       (SELECT count(*) FROM orders AS o WHERE o.customer_id = c.customer_id) AS order_count\nFROM customers AS c\nWHERE c.customer_id BETWEEN 100 AND 149;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\" data-role=\"output\"><code>|--SEARCH c USING INTEGER PRIMARY KEY (rowid&gt;? AND rowid&lt;?)\n`--CORRELATED SCALAR SUBQUERY 1\n   `--SEARCH o USING COVERING INDEX orders_customer_idx (customer_id=?)</code></pre>\n<p>The subquery is still dependent, but each execution now reads about 20 index entries.</p>\n<h3>Replace NOT IN with NOT EXISTS</h3>\n<p><code>NOT EXISTS</code> only asks whether a matching row exists, so NULLs in the subquery do not change the answer and the engine can use an ordinary anti join:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT c.customer_id\nFROM customers AS c\nWHERE NOT EXISTS (SELECT 1 FROM referrals AS r WHERE r.referred_by = c.customer_id);</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Hash Right Anti Join  (cost=617.00..1069.75 rows=10000 width=4) (actual rows=10000.00 loops=1)\n  Hash Cond: (r.referred_by = c.customer_id)\n  -&gt;  Seq Scan on referrals r  (cost=0.00..289.00 rows=20000 width=4) (actual rows=20000.00 loops=1)\n  -&gt;  Hash  (cost=367.00..367.00 rows=20000 width=4) (actual rows=20000.00 loops=1)\n        Buckets: 32768  Batches: 1  Memory Usage: 960kB\n        -&gt;  Seq Scan on customers c  (cost=0.00..367.00 rows=20000 width=4) (actual rows=20000.00 loops=1)</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>EXPLAIN PLAN FOR\nSELECT c.customer_id\nFROM customers c\nWHERE NOT EXISTS (SELECT 1 FROM referrals r WHERE r.referred_by = c.customer_id);\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation             | Name        | Rows  | Bytes | Cost (%CPU)| Time     |\n|   0 | SELECT STATEMENT      |             | 10001 | 90009 |    28   (0)| 00:00:01 |\n|*  1 |  HASH JOIN RIGHT ANTI |             | 10001 | 90009 |    28   (0)| 00:00:01 |\n|*  2 |   TABLE ACCESS FULL   | REFERRALS   | 18000 | 72000 |    13   (0)| 00:00:01 |\n|   3 |   INDEX FAST FULL SCAN| SYS_C008720 | 20000 |    97K|    15   (0)| 00:00:01 |</code></pre>\n<p>The plan is an anti join and the query now returns the 10,000 customers who referred nobody. If you must keep <code>NOT IN</code>, add <code>WHERE referred_by IS NOT NULL</code> inside the subquery, or declare the column <code>NOT NULL</code> when the data allows it.</p>\n<h3>When to leave it alone</h3>\n<p>A dependent subquery that runs a handful of times, or that does one index lookup per row for a few thousand rows, is not a problem. Neither is a subquery the plan marks as executed once: PostgreSQL calls it an <code>InitPlan</code>, MySQL a <code>SUBQUERY</code> without \"dependent\". Rewrite when the repeat count multiplied by the cost of one run is a large share of the query.</p>","checklist_html":["Find the subquery block in the plan and read how many times it ran.","Multiply the rows one execution reads by that count.","Check whether each execution uses an index on the correlated column.","Rewrite as a join with GROUP BY when the outer query returns many rows.","Add an index on the correlated column when it returns few.","Replace NOT IN (subquery) with NOT EXISTS, or exclude NULLs in the subquery.","Compare results before and after: NOT IN and NOT EXISTS differ when NULLs are present."],"faqs":[{"question":"What is a dependent subquery in MySQL EXPLAIN?","answer":"It is a subquery that refers to a column of the outer query, so MySQL evaluates it again for each outer row. The select_type column shows DEPENDENT SUBQUERY. It is cheap when each evaluation is an index lookup and expensive when each one scans a table."},{"question":"Are correlated subqueries always slow?","answer":"No. Optimizers convert many of them into joins, and one that stays correlated is fine when it runs few times or uses an index each time. It is slow when a scan is repeated for thousands of outer rows."},{"question":"Why does NOT IN return no rows?","answer":"If the subquery returns even one NULL, the comparison with that NULL is unknown for every outer row, so no row can satisfy NOT IN and the result is empty. NOT EXISTS does not have this behavior, and neither does NOT IN once NULLs are filtered out of the subquery."},{"question":"Is NOT EXISTS faster than NOT IN?","answer":"When the subquery column allows NULL, usually yes, because NOT EXISTS can be executed as a plain anti join while NOT IN needs null-aware handling. When the column is declared NOT NULL, most engines produce the same plan for both. PostgreSQL is the exception: it does not turn NOT IN into an anti join, so NOT EXISTS is the safer form there."},{"question":"Should I use a join or a subquery?","answer":"Write whichever is clearer and check the plan. If the plan shows the subquery being executed per row at volume, rewrite it as a join with GROUP BY or as EXISTS. If the optimizer has already turned it into a join, there is nothing to gain from rewriting."}],"plan_group":"Joins and subqueries","related_slugs":["join-algorithms","join-row-explosion","full-table-scan"]},"source_url":"https://sqlly.app/sql-performance/correlated-subquery","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/cte-materialization","corpus":"sql-performance","engine":null,"language":"en","title":"Materialized CTEs","description":"A materialized CTE is computed in full before the outer filter applies. How to spot CTE Scan in a plan and use NOT MATERIALIZED to push the filter down.","body":{"slug":"cte-materialization","engines":["PostgreSQL","MySQL"],"symptoms":["Slow query"],"h1":"Materialized CTEs","lede":"PostgreSQL computes a materialized CTE in full and only then applies the filters of the outer query. How to recognise CTE Scan with rows removed by a filter, when PostgreSQL materializes, and how NOT MATERIALIZED lets the filter reach the index.","symptom_html":"<p>A common table expression (a <code>WITH</code> query) can be executed in two ways. The engine can fold it into the outer query, as if you had written a subquery, so that outer filters reach the tables and their indexes. Or it can run the CTE once, keep the whole result, and read from that copy. The second way is materialization. It is right when the result is needed several times in full. It is wasteful when the outer query wants a few rows, because the filter is applied to the stored result after all the work has been done.</p>\n<p>The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> flags PostgreSQL plans where a <code>CTE Scan</code> throws away most of what the CTE produced. The examples use a shop schema with 400,000 orders and an index on <code>orders (customer_id)</code>.</p>","diagnosis_html":"<h3>A CTE referenced once is folded in</h3>\n<p>PostgreSQL inlines a plain <code>SELECT</code> CTE that the query refers to once. The filter on <code>customer_id</code> goes straight to the index and there is no <code>CTE Scan</code> in the plan:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nEXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nWITH customer_totals AS (\n    SELECT customer_id, count(*) AS orders, sum(total) AS spent\n    FROM orders\n    GROUP BY customer_id\n)\nSELECT * FROM customer_totals WHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>GroupAggregate  (cost=4.59..84.65 rows=1 width=44) (actual rows=1.00 loops=1)\n  -&gt;  Bitmap Heap Scan on orders  (cost=4.59..84.54 rows=21 width=10) (actual rows=20.00 loops=1)\n        Recheck Cond: (customer_id = 4242)\n        Heap Blocks: exact=20\n        -&gt;  Bitmap Index Scan on orders_customer_idx  (cost=0.00..4.58 rows=21 width=0) (actual rows=20.00 loops=1)\n              Index Cond: (customer_id = 4242)\n              Index Searches: 1</code></pre>\n<h3>A CTE referenced twice is materialized</h3>\n<p>Refer to the same CTE a second time and PostgreSQL computes it once and stores it:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nWITH customer_totals AS (\n    SELECT customer_id, count(*) AS orders, sum(total) AS spent\n    FROM orders\n    GROUP BY customer_id\n)\nSELECT a.spent AS spent_4242, b.spent AS spent_4243\nFROM customer_totals AS a\nCROSS JOIN customer_totals AS b\nWHERE a.customer_id = 4242 AND b.customer_id = 4243;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Nested Loop  (cost=11700.51..12487.17 rows=1 width=64) (actual rows=1.00 loops=1)\n  CTE customer_totals\n    -&gt;  HashAggregate  (cost=11482.00..11700.51 rows=17481 width=44) (actual rows=18001.00 loops=1)\n          Group Key: orders.customer_id\n          Batches: 1  Memory Usage: 7185kB\n          -&gt;  Seq Scan on orders  (cost=0.00..8482.00 rows=400000 width=10) (actual rows=400000.00 loops=1)\n  -&gt;  CTE Scan on customer_totals a  (cost=0.00..393.32 rows=1 width=32) (actual rows=1.00 loops=1)\n        Filter: (customer_id = 4242)\n        Rows Removed by Filter: 18000\n        Storage: Memory  Maximum Storage: 1100kB\n  -&gt;  CTE Scan on customer_totals b  (cost=0.00..393.32 rows=1 width=32) (actual rows=1.00 loops=1)\n        Filter: (customer_id = 4243)\n        Rows Removed by Filter: 18000\n        Storage: Memory  Maximum Storage: 1100kB</code></pre>\n<p>The signs are the <code>CTE customer_totals</code> block, which reads all 400,000 orders and builds a row for every customer, and the <code>CTE Scan</code> nodes with a <code>Filter</code> and a large <code>Rows Removed by Filter</code>. Two customers were asked for and the totals of all of them were computed.</p>\n<p>The keyword <code>MATERIALIZED</code> forces the same behavior for a CTE that is referenced once, so check for it in the query text when a plan has an unexpected <code>CTE Scan</code>.</p>\n<h3>MySQL: Materialize CTE</h3>\n<p>MySQL also materializes a CTE that is used more than once and says so in the tree format:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nEXPLAIN FORMAT=TREE\nWITH customer_totals AS (\n    SELECT customer_id, count(*) AS orders, sum(total) AS spent\n    FROM orders\n    GROUP BY customer_id\n)\nSELECT a.spent AS spent_4242, b.spent AS spent_4243\nFROM customer_totals AS a\nCROSS JOIN customer_totals AS b\nWHERE a.customer_id = 4242 AND b.customer_id = 4243;</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Nested loop inner join  (cost=32.8e+6 rows=327e+6)\n    -&gt; Index lookup on a using &lt;auto_key0&gt; (customer_id=4242)  (cost=81897..81900 rows=10)\n        -&gt; Materialize CTE customer_totals if needed  (cost=81896..81896 rows=18075)\n            -&gt; Group aggregate: count(0), sum(orders.total)  (cost=80089 rows=18075)\n                -&gt; Index scan on orders using orders_customer_idx  (cost=40225 rows=398641)\n    -&gt; Index lookup on b using &lt;auto_key0&gt; (customer_id=4243)  (cost=81897..81899 rows=10)\n        -&gt; Materialize CTE customer_totals if needed (query plan printed elsewhere)  (cost=81896..81896 rows=18075)</code></pre>\n<p>MySQL builds the temporary result once, adds an automatic key (<code>&lt;auto_key0&gt;</code>) and looks both customers up in it. The lookups are fast, but the whole of <code>orders</code> is still read and aggregated to build it.</p>","fix_html":"<h3>Add NOT MATERIALIZED</h3>\n<p>In PostgreSQL, <code>NOT MATERIALIZED</code> tells the planner to fold the CTE into each place it is used. Each reference then gets its own filter and its own index scan:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nWITH customer_totals AS NOT MATERIALIZED (\n    SELECT customer_id, count(*) AS orders, sum(total) AS spent\n    FROM orders\n    GROUP BY customer_id\n)\nSELECT a.spent AS spent_4242, b.spent AS spent_4243\nFROM customer_totals AS a\nCROSS JOIN customer_totals AS b\nWHERE a.customer_id = 4242 AND b.customer_id = 4243;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Nested Loop  (cost=9.17..169.23 rows=1 width=64) (actual rows=1.00 loops=1)\n  -&gt;  GroupAggregate  (cost=4.59..84.60 rows=1 width=44) (actual rows=1.00 loops=1)\n        -&gt;  Bitmap Heap Scan on orders  (cost=4.59..84.54 rows=21 width=10) (actual rows=20.00 loops=1)\n              Recheck Cond: (customer_id = 4242)\n              Heap Blocks: exact=20\n              -&gt;  Bitmap Index Scan on orders_customer_idx  (cost=0.00..4.58 rows=21 width=0) (actual rows=20.00 loops=1)\n                    Index Cond: (customer_id = 4242)\n                    Index Searches: 1\n  -&gt;  GroupAggregate  (cost=4.59..84.60 rows=1 width=44) (actual rows=1.00 loops=1)\n        -&gt;  Bitmap Heap Scan on orders orders_1  (cost=4.59..84.54 rows=21 width=10) (actual rows=20.00 loops=1)\n              Recheck Cond: (customer_id = 4243)\n              Heap Blocks: exact=20\n              -&gt;  Bitmap Index Scan on orders_customer_idx  (cost=0.00..4.58 rows=21 width=0) (actual rows=20.00 loops=1)\n                    Index Cond: (customer_id = 4243)\n                    Index Searches: 1</code></pre>\n<p>The CTE is now evaluated twice, once per reference, and each evaluation reads 20 rows instead of 400,000.</p>\n<h3>Move the filter into the CTE</h3>\n<p>When the CTE has to stay materialized, filter inside it so that less is computed and stored. This works in every engine:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nWITH customer_totals AS (\n    SELECT customer_id, count(*) AS orders, sum(total) AS spent\n    FROM orders\n    WHERE customer_id IN (4242, 4243)\n    GROUP BY customer_id\n)\nSELECT a.spent AS spent_4242, b.spent AS spent_4243\nFROM customer_totals AS a\nCROSS JOIN customer_totals AS b\nWHERE a.customer_id = 4242 AND b.customer_id = 4243;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Nested Loop  (cost=163.94..165.79 rows=1 width=64) (actual rows=1.00 loops=1)\n  CTE customer_totals\n    -&gt;  GroupAggregate  (cost=163.02..163.94 rows=41 width=44) (actual rows=2.00 loops=1)\n          Group Key: orders.customer_id\n          -&gt;  Sort  (cost=163.02..163.12 rows=41 width=10) (actual rows=40.00 loops=1)\n                Sort Key: orders.customer_id\n                Sort Method: quicksort  Memory: 26kB\n                -&gt;  Bitmap Heap Scan on orders  (cost=9.17..161.92 rows=41 width=10) (actual rows=40.00 loops=1)\n                      Recheck Cond: (customer_id = ANY ('{4242,4243}'::integer[]))\n                      Heap Blocks: exact=40\n                      -&gt;  Bitmap Index Scan on orders_customer_idx  (cost=0.00..9.16 rows=41 width=0) (actual rows=40.00 loops=1)\n                            Index Cond: (customer_id = ANY ('{4242,4243}'::integer[]))\n                            Index Searches: 1\n  -&gt;  CTE Scan on customer_totals a  (cost=0.00..0.92 rows=1 width=32) (actual rows=1.00 loops=1)\n        Filter: (customer_id = 4242)\n        Rows Removed by Filter: 1\n        Storage: Memory  Maximum Storage: 17kB\n  -&gt;  CTE Scan on customer_totals b  (cost=0.00..0.92 rows=1 width=32) (actual rows=1.00 loops=1)\n        Filter: (customer_id = 4243)\n        Rows Removed by Filter: 1\n        Storage: Memory  Maximum Storage: 17kB</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN FORMAT=TREE\nWITH customer_totals AS (\n    SELECT customer_id, count(*) AS orders, sum(total) AS spent\n    FROM orders\n    WHERE customer_id IN (4242, 4243)\n    GROUP BY customer_id\n)\nSELECT a.spent AS spent_4242, b.spent AS spent_4243\nFROM customer_totals AS a\nCROSS JOIN customer_totals AS b\nWHERE a.customer_id = 4242 AND b.customer_id = 4243;</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Nested loop inner join  (cost=192 rows=1600)\n    -&gt; Index lookup on a using &lt;auto_key0&gt; (customer_id=4242)  (cost=26.9..27.9 rows=4)\n        -&gt; Materialize CTE customer_totals if needed  (cost=26.5..26.5 rows=40)\n            -&gt; Group aggregate: count(0), sum(orders.total)  (cost=22.5 rows=40)\n                -&gt; Index range scan on orders using orders_customer_idx over (customer_id = 4242) OR (customer_id = 4243), with index condition: (orders.customer_id in (4242,4243))  (cost=18.5 rows=40)\n    -&gt; Index lookup on b using &lt;auto_key0&gt; (customer_id=4243)  (cost=26.8..27.6 rows=4)\n        -&gt; Materialize CTE customer_totals if needed (query plan printed elsewhere)  (cost=26.5..26.5 rows=40)</code></pre>\n<h3>When to leave it alone</h3>\n<p>Materialization is the better plan when the CTE is expensive, is used several times, and each use needs most of its rows: computing it once is cheaper than computing it for every reference. It is also a deliberate tool. Writing <code>AS MATERIALIZED</code> stops the planner from merging the CTE into a join order that its estimates get wrong, which is one of the fixes for a <a href=\"/sql-performance/row-estimate-mismatch#row-goals-top-and-limit\">row goal that backfires</a>. Leave a <code>CTE Scan</code> alone when it removes few rows.</p>","checklist_html":["Look for CTE Scan nodes and the CTE block that feeds them.","Compare the rows the CTE produced with the rows the CTE Scan kept.","Count how many times the query refers to the CTE and check for the MATERIALIZED keyword.","Try NOT MATERIALIZED and compare the plans.","Or move the filter inside the CTE.","Keep materialization when the full result is used more than once."],"faqs":[{"question":"What does CTE Scan mean in a PostgreSQL plan?","answer":"It reads from the stored result of a materialized CTE. The CTE itself appears as a separate block in the plan and is executed once. Any filter shown on the CTE Scan is applied to the stored result, after the CTE has been computed in full."},{"question":"When does PostgreSQL materialize a CTE?","answer":"When the query refers to the CTE more than once, when it is marked MATERIALIZED, when it is recursive, or when it is not a plain SELECT without side effects. A simple SELECT CTE that is referenced once is folded into the outer query."},{"question":"What does NOT MATERIALIZED do?","answer":"It asks PostgreSQL to fold the CTE into the outer query at every place it is referenced, so that filters and join conditions from the outer query can be used inside it. The CTE is then evaluated once per reference instead of once in total."},{"question":"Are CTEs slower than subqueries?","answer":"Not when the engine folds them in: the plan is then the same as for a subquery. They are slower only when materialization computes more rows than the outer query needs. Check the plan for CTE Scan in PostgreSQL or Materialize CTE in MySQL."},{"question":"Does SQL Server materialize CTEs?","answer":"No. SQL Server always expands a CTE into the query where it is used, so a CTE referenced twice is evaluated twice. To compute an intermediate result once in SQL Server, store it in a temporary table."}],"plan_group":"Joins and subqueries","related_slugs":["correlated-subquery","row-estimate-mismatch","full-table-scan"]},"source_url":"https://sqlly.app/sql-performance/cte-materialization","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/execution-plan-operators","corpus":"sql-performance","engine":null,"language":"en","title":"Execution plan operators","description":"What each kind of execution plan operator does, what the engines call it, when it is fine and when it is the reason a query is slow.","body":{"slug":"execution-plan-operators","engines":["SQL Server","PostgreSQL","MySQL","SQLite","Oracle"],"symptoms":["Slow query"],"h1":"Execution plan operators","lede":"Every step in an execution plan is an operator: something that reads rows, joins them, sorts them or passes them on. The engines use different names for the same two dozen ideas. This page lists them by what they do.","symptom_html":"<p>An execution plan is a tree of operators. Each one takes rows from the operators beneath it, does one job and hands rows to the one above. SQL Server, PostgreSQL, MySQL, Oracle and SQLite each have their own names, but the jobs are the same everywhere: read a table, find rows through an index, join two inputs, sort, group, and so on.</p>\n<p>The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> labels every step of a plan with one of the kinds below. If you have not read a plan before, start with <a href=\"/sql-performance/reading-execution-plans\">how to read an execution plan</a>. The two examples use a shop schema with 20,000 customers and 400,000 orders.</p>","diagnosis_html":"<h3>How to see the operators</h3>\n<p>Each engine has one command that prints the tree. PostgreSQL's <code>EXPLAIN</code> (estimates) and <code>EXPLAIN ANALYZE</code> (actuals) produce the plan the examples in this page show. The other four:</p>\n<h3>SQL Server: the actual plan</h3>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS XML ON;\n-- your query here</code></pre>\n<p>The plan XML arrives as an extra result set and names every operator. <code>SET SHOWPLAN_XML ON</code> gives the estimated plan without running the statement.</p>\n<h3>MySQL: the iterator tree</h3>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN ANALYZE\nSELECT * FROM orders WHERE customer_id = 42;</code></pre>\n<p>MySQL 8.0.18 and later print the tree of iterators with actual times and rows beside the estimates; on older servers, plain <code>EXPLAIN</code> shows the same tree from estimates alone.</p>\n<h3>SQLite: the query plan</h3>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>EXPLAIN QUERY PLAN\nSELECT * FROM orders WHERE customer_id = 42;</code></pre>\n<p>The output is a short list of steps per table, using the SCAN and SEARCH vocabulary described below.</p>\n<h3>Oracle: the plan table</h3>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>EXPLAIN PLAN FOR\nSELECT * FROM orders WHERE customer_id = 42;\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY(NULL, NULL, 'BASIC'));</code></pre>\n<p><code>BASIC</code> prints just the tree of operator names; drop the format argument for costs, rows and the predicate detail.</p>\n<h3>Scan</h3>\n<p>Reads a whole table or a whole index, row after row, and keeps the rows that pass the filter. Names: <code>Table Scan</code>, <code>Clustered Index Scan</code> and <code>Index Scan</code> in SQL Server; <code>Seq Scan</code> in PostgreSQL; <code>Table scan</code> and <code>Index scan</code> in MySQL (<code>ALL</code> and <code>index</code> in the tabular format); <code>TABLE ACCESS FULL</code> and <code>INDEX FULL SCAN</code> in Oracle; <code>SCAN</code> in SQLite.</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN SELECT * FROM customers WHERE country = 'DE';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Seq Scan on customers  (cost=0.00..417.00 rows=4000 width=36)\n  Filter: (country = 'DE'::bpchar)</code></pre>\n<p>A scan is the right choice when the query needs a large share of the table, or the table is small. It is a problem when it reads many rows to return few; see <a href=\"/sql-performance/full-table-scan\">full table scan</a>.</p>\n<h3>Seek</h3>\n<p>Goes through an index to the rows that match a condition and reads only those. Names: <code>Index Seek</code> and <code>Clustered Index Seek</code> in SQL Server; <code>Index Scan</code>, <code>Index Only Scan</code> and <code>Bitmap Index Scan</code> in PostgreSQL; <code>Index lookup</code>, <code>Single-row index lookup</code> and <code>Index range scan</code> in MySQL (<code>ref</code>, <code>eq_ref</code>, <code>const</code> and <code>range</code> in the tabular format); <code>INDEX UNIQUE SCAN</code> and <code>INDEX RANGE SCAN</code> in Oracle; <code>SEARCH</code> in SQLite.</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN SELECT * FROM orders WHERE order_id = 42;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Index Scan using orders_pkey on orders  (cost=0.42..8.44 rows=1 width=37)\n  Index Cond: (order_id = 42)</code></pre>\n<p>The name is a trap in PostgreSQL: an <code>Index Scan</code> there is usually a seek, and the <code>Index Cond</code> line shows the condition it searched with. A seek is only as good as that condition. One that matches a large range still reads a large range; check the row count on the step. When a seek you expected did not happen, see <a href=\"/sql-performance/index-not-used\">index not used</a> and <a href=\"/sql-performance/non-sargable-predicates\">non-sargable predicates</a>.</p>\n<h3>Lookup</h3>\n<p>Fetches the rest of a row from the table after an index found it, because the index does not hold every column the query needs. Names: <code>Key Lookup</code> and <code>RID Lookup</code> in SQL Server; <code>Bitmap Heap Scan</code> in PostgreSQL, where a plain <code>Index Scan</code> also includes the table fetch; <code>TABLE ACCESS BY INDEX ROWID</code> in Oracle. MySQL and SQLite do not show the fetch as a step of its own; an index that avoids it is marked as a covering index.</p>\n<p>A lookup costs one table visit per row. A few hundred are free, a few hundred thousand are not; see <a href=\"/sql-performance/key-lookup\">key lookups</a> and, for PostgreSQL, <a href=\"/sql-performance/index-only-scan-heap-fetches\">index-only scans and heap fetches</a>.</p>\n<h3>Nested loop join</h3>\n<p>For each row of the outer input, finds the matching rows in the inner input. Names: <code>Nested Loops</code> in SQL Server and Oracle, <code>Nested Loop</code> in PostgreSQL, <code>Nested loop inner join</code> in MySQL. SQLite joins this way and shows it as one line per table, in loop order.</p>\n<p>It is the best join when the outer input is small and the inner side has an index to search. It is the worst one when the outer input is large, because the inner side runs once per row. <a href=\"/sql-performance/join-algorithms\">Join algorithms</a> covers how to tell.</p>\n<h3>Hash join</h3>\n<p>Reads one input into an in-memory hash table, then reads the other and probes the table for matches. Names: <code>Hash Match</code> in SQL Server, <code>Hash Join</code> in PostgreSQL, <code>Inner hash join</code> in MySQL, <code>HASH JOIN</code> in Oracle. Good for joining two large inputs with no useful order. Watch the build side: if it is larger than the memory it was given, the join writes to disk; see <a href=\"/sql-performance/sort-and-hash-spills\">sort and hash spills</a>.</p>\n<h3>Merge join</h3>\n<p>Walks two inputs that are sorted on the join columns and matches them in one pass. Names: <code>Merge Join</code> in SQL Server and PostgreSQL, <code>MERGE JOIN</code> in Oracle. Cheap when both inputs arrive sorted from an index. When the plan has to add a sort beneath it to get that order, the sort is where the cost is.</p>\n<h3>Other joins and cross products</h3>\n<p>Joins whose method is chosen at run time, such as SQL Server's <code>Adaptive Join</code>, and joins with no join condition, such as Oracle's <code>MERGE JOIN CARTESIAN</code>. A cross product pairs every row of one input with every row of the other. Unless you wrote <code>CROSS JOIN</code> on purpose, look for a missing join condition; see <a href=\"/sql-performance/join-row-explosion\">join row explosion</a>.</p>\n<h3>Sort</h3>\n<p>Puts rows in order for <code>ORDER BY</code>, and for operators above it that need sorted input. Names: <code>Sort</code> in SQL Server, PostgreSQL and MySQL (<code>Using filesort</code> in MySQL's tabular format); <code>SORT ORDER BY</code> in Oracle; <code>USE TEMP B-TREE FOR ORDER BY</code> in SQLite. A sort has to see every input row before it returns the first one, and it needs memory in proportion to its input. An index in the right order removes it; see <a href=\"/sql-performance/expensive-sort\">expensive sorts</a>.</p>\n<h3>Aggregate</h3>\n<p>Computes <code>GROUP BY</code>, <code>DISTINCT</code> and aggregate functions such as <code>count</code> and <code>sum</code>. There are two methods. A hash aggregate (<code>Hash Match (Aggregate)</code>, <code>HashAggregate</code>, <code>HASH GROUP BY</code>) builds one entry per group in memory. A stream aggregate (<code>Stream Aggregate</code>, <code>GroupAggregate</code>, <code>SORT GROUP BY</code>) reads input already sorted by the grouping columns. MySQL prints <code>Aggregate using temporary table</code> or <code>Group aggregate</code>, and SQLite <code>USE TEMP B-TREE FOR GROUP BY</code>. See <a href=\"/sql-performance/using-temporary\">Using temporary</a> for the MySQL case.</p>\n<h3>Window</h3>\n<p>Computes window functions: anything with <code>OVER (...)</code>. Names: <code>Sequence Project</code>, <code>Window Spool</code> and <code>Window Aggregate</code> in SQL Server; <code>WindowAgg</code> in PostgreSQL; <code>Window aggregate</code> in MySQL; <code>WINDOW SORT</code> and <code>WINDOW BUFFER</code> in Oracle. The window operator is usually cheap. The sort beneath it, on the <code>PARTITION BY</code> and <code>ORDER BY</code> columns, is usually not.</p>\n<h3>Spool and materialize</h3>\n<p>Saves rows so the plan can read them again without recomputing them. Names: <code>Table Spool</code>, <code>Index Spool</code> and <code>Row Count Spool</code> in SQL Server; <code>Materialize</code>, <code>Memoize</code> and <code>Hash</code> (the build step of a hash join) in PostgreSQL; <code>Materialize</code> and <code>Temporary table</code> in MySQL; <code>TEMP TABLE TRANSFORMATION</code> and <code>BUFFER SORT</code> in Oracle; <code>MATERIALIZE</code> in SQLite. A spool that builds an index is the engine making the index it could not find; see <a href=\"/sql-performance/index-spool-automatic-index\">index spools and automatic indexes</a>. For a CTE that is computed in full before it is filtered, see <a href=\"/sql-performance/cte-materialization\">CTE materialization</a>.</p>\n<h3>Parallelism</h3>\n<p>Moves rows between the threads or processes of a parallel plan. Names: <code>Parallelism</code> with <code>Gather Streams</code>, <code>Distribute Streams</code> or <code>Repartition Streams</code> in SQL Server; <code>Gather</code> and <code>Gather Merge</code> in PostgreSQL; the <code>PX</code> steps in Oracle. Everything beneath one runs in several workers at once. <a href=\"/sql-performance/parallel-query-plans\">Parallel query plans</a> covers workers that never started and rows that all landed on one thread.</p>\n<h3>Filter</h3>\n<p>Discards rows that fail a condition which no operator beneath it could apply. Names: <code>Filter</code> in SQL Server, MySQL and Oracle. PostgreSQL shows it as a <code>Filter</code> line on another step, with <code>Rows Removed by Filter</code> next to it. A filter that removes most of its input high in the plan means the rows were read, and perhaps joined and sorted, before they were thrown away. Look for a way to apply the condition earlier, usually with an index.</p>\n<h3>Compute</h3>\n<p>Evaluates expressions for each row. Names: <code>Compute Scalar</code> and <code>Segment</code> in SQL Server. Most other engines fold expressions into the neighbouring steps. Normally free. In SQL Server it is also where a scalar function runs once per row; see <a href=\"/sql-performance/scalar-udf\">scalar functions</a>.</p>\n<h3>Modify</h3>\n<p>Writes: <code>INSERT</code>, <code>UPDATE</code>, <code>DELETE</code> and <code>MERGE</code>. Names: <code>Clustered Index Insert</code>, <code>Table Update</code> and their relatives in SQL Server; <code>Insert</code>, <code>Update</code> and <code>Delete</code> in PostgreSQL. In SQL Server each index that has to be maintained can show as its own step, which is a direct view of what an extra index costs on write.</p>\n<h3>Remote</h3>\n<p>Work done on another server. Names: <code>Remote Query</code> and <code>Remote Scan</code> in SQL Server (linked servers), <code>Foreign Scan</code> in PostgreSQL (foreign data wrappers), <code>REMOTE</code> in Oracle (database links). The local optimizer knows little about the remote table, and rows cross the network. Check which conditions were sent to the remote side and which were applied after the rows came back.</p>\n<h3>Set operations</h3>\n<p>Combines the results of several inputs: <code>UNION</code>, <code>UNION ALL</code>, <code>INTERSECT</code> and <code>EXCEPT</code>, and reading the partitions of a partitioned table. Names: <code>Concatenation</code> in SQL Server, <code>Append</code> and <code>Merge Append</code> in PostgreSQL, <code>UNION-ALL</code> in Oracle, <code>COMPOUND QUERY</code> in SQLite. <code>UNION</code> without <code>ALL</code> adds a sort or hash to remove duplicates. For an <code>Append</code> over more partitions than the query needs, see <a href=\"/sql-performance/partition-pruning\">partition pruning</a>.</p>\n<h3>Limit</h3>\n<p>Stops after a number of rows. Names: <code>Top</code> in SQL Server, <code>Limit</code> in PostgreSQL and MySQL, <code>COUNT STOPKEY</code> in Oracle. A limit changes the plan beneath it, because the optimizer picks operators that return the first rows quickly. When it guesses wrong about how soon those rows turn up, the query is slower with the limit than without; see <a href=\"/sql-performance/row-estimate-mismatch#row-goals-top-and-limit\">row goals</a>.</p>\n<h3>Subquery</h3>\n<p>A subquery, CTE, derived table or view that is evaluated as a unit. Names: <code>Subquery Scan</code> and <code>CTE Scan</code> in PostgreSQL; <code>Materialize CTE</code> and the <code>DEPENDENT SUBQUERY</code> select type in MySQL; <code>VIEW</code> in Oracle; <code>CO-ROUTINE</code>, <code>SCALAR SUBQUERY</code> and <code>CORRELATED SCALAR SUBQUERY</code> in SQLite. SQL Server has no such operator; it turns subqueries into joins. What matters is how many times the unit runs. See <a href=\"/sql-performance/correlated-subquery\">correlated subqueries</a>.</p>\n<h3>Table function</h3>\n<p>Rows produced by a function: a table-valued function, <code>generate_series</code>, <code>unnest</code>, a JSON table. Names: <code>Table Valued Function</code> in SQL Server, <code>Function Scan</code> in PostgreSQL, <code>COLLECTION ITERATOR</code> in Oracle. The optimizer often cannot tell how many rows a function returns and uses a fixed guess, so check the estimate on this step against the actual count; see <a href=\"/sql-performance/row-estimate-mismatch\">row estimates that are far off</a>.</p>\n<h3>Constant</h3>\n<p>Rows that come from the query text and not from a table: a <code>VALUES</code> list, a <code>SELECT</code> with no <code>FROM</code>. Names: <code>Constant Scan</code> in SQL Server, <code>Result</code> and <code>Values Scan</code> in PostgreSQL, <code>FAST DUAL</code> in Oracle. Nothing to tune.</p>\n<h3>Result</h3>\n<p>The root of the plan, which returns rows to the client. Oracle prints it as <code>SELECT STATEMENT</code> and SQLite as <code>QUERY PLAN</code>. Its cost and time are the totals for the statement.</p>\n<h3>Lock</h3>\n<p>Locks the rows a query selected, for <code>SELECT ... FOR UPDATE</code>. Names: <code>LockRows</code> in PostgreSQL, <code>FOR UPDATE</code> in Oracle. If this step is slow the query is waiting for another session; see <a href=\"/sql-performance/blocking-deadlocks\">blocking and deadlocks</a>.</p>\n<h3>Other</h3>\n<p>Steps that fit none of the above, such as Oracle's <code>PARTITION RANGE</code> steps, which choose the partitions to read, and SQL Server's cursor operators. They rarely cost anything themselves. Read the steps beneath them.</p>","fix_html":"<h3>Judge an operator by its numbers</h3>\n<p>No operator is bad by itself. What tells you whether one is a problem is in its numbers: how many rows went in against how many came out, how many times it ran, how the estimated row count compares with the actual one, and whether it wrote to disk. A scan that returns most of what it read is fine; a seek that ran 400,000 times is not.</p>\n<p>The usual fixes, in the order worth trying: give the operator fewer rows by adding or changing an index, rewrite the condition so an index can be used, correct the statistics so the optimizer chooses a different operator, and only then reach for hints or settings.</p>\n<p>Worked through on the shop schema: with no index on <code>email</code>, a point lookup on customers scans all 20,000 rows. The index and the re-check:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX idx_customers_email ON customers (email);\n\nEXPLAIN SELECT * FROM customers WHERE email = 'ana@example.com';</code></pre>\n<p>The plan reads <code>idx_customers_email</code> for one row instead of scanning the table. The same move exists on every engine - an index on the predicate columns turns a scan into a seek - and each guide linked from an operator above carries the engine's version.</p>\n<h3>When to leave it alone</h3>\n<p>If the step's share of the total time is small, it is not the step to work on, whatever it is called. Start from the time, find the step that owns it, and then use this page to see what that step does.</p>","checklist_html":["Find the step with the most time of its own before looking at operator names.","Scan: compare rows read with rows returned.","Seek: check the condition it searched with and the row count.","Lookup and nested loop: check how many times the step ran.","Sort, hash join and aggregate: check for a spill to disk.","Compare estimated and actual rows on every step."],"faqs":[{"question":"What is the difference between an index scan and an index seek?","answer":"A seek uses the index to go straight to the rows that match a condition and reads only those. A scan reads the whole index from one end to the other. SQL Server uses exactly these names. In PostgreSQL an Index Scan with an Index Cond line is a seek."},{"question":"Is a table scan always bad?","answer":"No. A scan is the cheapest way to read a small table or most of a large one. It is a problem when the step reads many rows and returns few, which means an index could have found those rows directly."},{"question":"What is a Hash Match in SQL Server?","answer":"Hash Match is SQL Server's operator for hash joins and hash aggregates. It builds a hash table in memory from one input, then probes it with the other input or uses it to group rows. The same operator appears as Hash Join and HashAggregate in PostgreSQL."},{"question":"What does Bitmap Heap Scan mean in PostgreSQL?","answer":"A Bitmap Index Scan first collects the locations of all matching rows from an index. The Bitmap Heap Scan then fetches those rows from the table in physical order. PostgreSQL uses the pair when a condition matches too many rows for a plain index scan and too few for a sequential scan."},{"question":"What does SEARCH mean in a SQLite query plan?","answer":"SEARCH means SQLite uses an index or the primary key to find the rows for that table. SCAN means it reads the whole table or a whole index."}],"plan_group":"Reading the plan","related_slugs":["reading-execution-plans","join-algorithms","full-table-scan"]},"source_url":"https://sqlly.app/sql-performance/execution-plan-operators","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/expensive-sort","corpus":"sql-performance","engine":null,"language":"en","title":"Expensive sort operators","description":"A Sort operator or Using filesort means the rows were sorted at query time. How to tell when it matters and how an index can deliver the order for free.","body":{"slug":"expensive-sort","engines":["PostgreSQL","MySQL","SQL Server","Oracle","SQLite"],"symptoms":["Slow query","High CPU"],"h1":"Expensive sort operators","lede":"ORDER BY, GROUP BY, DISTINCT and merge joins all need sorted rows. If no index supplies the order, the engine sorts at query time. How to spot the sort, judge its cost, and remove it with an index that matches the ORDER BY.","symptom_html":"<p>A sort in a plan means the engine collected rows and put them in order while the query ran. It appears as <code>Sort</code> in PostgreSQL and SQL Server, <code>Using filesort</code> in MySQL, <code>SORT ORDER BY</code> in Oracle and <code>USE TEMP B-TREE FOR ORDER BY</code> in SQLite. Sorting needs every input row before it can return the first one, uses memory in proportion to the input, and writes to disk when the memory runs out.</p>\n<p>The sort that hurts most is the one behind \"latest 20\" queries: the engine reads and sorts thousands of rows to return a handful. An index that stores rows in the wanted order lets it read the 20 rows and stop. The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> flags sorts that take a large share of the query. The examples use a shop schema with 400,000 orders, 40,000 of them for customer 1.</p>","diagnosis_html":"<h3>Find the sort and count its input</h3>\n<p>The query asks for one customer's 20 most recent orders. With no useful index, PostgreSQL reads all of the customer's rows and sorts them:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT order_id, order_date, total FROM orders\nWHERE customer_id = 1\nORDER BY order_date DESC LIMIT 20;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Limit  (cost=8009.29..8011.62 rows=20 width=18) (actual rows=20.00 loops=1)\n  -&gt;  Gather Merge  (cost=8009.29..12672.49 rows=40039 width=18) (actual rows=20.00 loops=1)\n        Workers Planned: 2\n        Workers Launched: 2\n        -&gt;  Sort  (cost=7009.26..7050.97 rows=16683 width=18) (actual rows=16.33 loops=3)\n              Sort Key: order_date DESC\n              Sort Method: top-N heapsort  Memory: 27kB\n              Worker 0:  Sort Method: top-N heapsort  Memory: 27kB\n              Worker 1:  Sort Method: top-N heapsort  Memory: 27kB\n              -&gt;  Parallel Seq Scan on orders  (cost=0.00..6565.33 rows=16683 width=18) (actual rows=13333.33 loops=3)\n                    Filter: (customer_id = 1)\n                    Rows Removed by Filter: 120000</code></pre>\n<p><code>Sort Method</code> says how the sort ran. <code>top-N heapsort</code> keeps only the best 20 rows in memory and is cheap in memory, but it still reads every input row. <code>quicksort</code> sorted everything in memory, and <code>external merge</code> went to disk, which is covered under <a href=\"/sql-performance/sort-and-hash-spills\">sort and hash spills</a>.</p>\n<p>MySQL reports the sort in the <code>Extra</code> column:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN SELECT order_id, order_date, total FROM orders\nWHERE customer_id = 1\nORDER BY order_date DESC LIMIT 20\\G</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code> type: ALL\n  key: NULL\n rows: 399054\nExtra: Using where; Using filesort</code></pre>\n<p>Oracle shows <code>SORT ORDER BY STOPKEY</code> when the sort only has to keep the first rows:</p>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>EXPLAIN PLAN FOR\nSELECT order_id, order_date, total FROM orders\nWHERE customer_id = 1\nORDER BY order_date DESC FETCH FIRST 20 ROWS ONLY;\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation               | Name   | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |\n|   0 | SELECT STATEMENT        |        |    20 |   360 |       |   927   (1)| 00:00:01 |\n|*  1 |  COUNT STOPKEY          |        |       |       |       |            |          |\n|   2 |   VIEW                  |        | 40234 |   707K|       |   927   (1)| 00:00:01 |\n|*  3 |    SORT ORDER BY STOPKEY|        | 40234 |   903K|  1440K|   927   (1)| 00:00:01 |\n|*  4 |     TABLE ACCESS FULL   | ORDERS | 40234 |   903K|       |   650   (1)| 00:00:01 |</code></pre>\n<p>SQLite builds a temporary B-tree to do the ordering:</p>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>EXPLAIN QUERY PLAN\nSELECT order_id, order_date, total FROM orders\nWHERE customer_id = 1\nORDER BY order_date DESC LIMIT 20;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\" data-role=\"output\"><code>|--SCAN orders\n`--USE TEMP B-TREE FOR ORDER BY</code></pre>\n<p>In SQL Server the operator is <code>Sort</code>, or <code>Sort</code> with the logical operation <code>TopN Sort</code> when the query has <code>TOP</code>:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS IO ON;\nSET STATISTICS XML ON;\nGO\nSELECT TOP (20) OrderId, OrderDate, Total FROM dbo.Orders\nWHERE CustomerId = 1\nORDER BY OrderDate DESC;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 8, logical reads 2709, physical reads 0</code></pre>\n<h3>Decide whether the sort is the cost</h3>\n<p>Compare the rows going into the sort with the rows the query returns. Sorting 40,000 rows to return 20 is waste an index can remove. Sorting 200 rows is nothing. In a plan with timings, subtract the time of the sort's input from the time of the sort itself; often the scan below is the slow part and the sort only looks expensive because it sits on top of it.</p>","fix_html":"<h3>Create an index that returns the rows in order</h3>\n<p>Put the equality columns from the <code>WHERE</code> clause first, then the <code>ORDER BY</code> columns. Within one customer the index is then already in date order, and the engine reads 20 entries from the end:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_customer_date_idx ON orders (customer_id, order_date);\n\nEXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT order_id, order_date, total FROM orders\nWHERE customer_id = 1\nORDER BY order_date DESC LIMIT 20;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Limit  (cost=0.42..9.91 rows=20 width=18) (actual rows=20.00 loops=1)\n  -&gt;  Index Scan Backward using orders_customer_date_idx on orders  (cost=0.42..19000.55 rows=40040 width=18) (actual rows=20.00 loops=1)\n        Index Cond: (customer_id = 1)\n        Index Searches: 1</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>CREATE INDEX orders_customer_date_idx ON orders (customer_id, order_date);\n\nEXPLAIN SELECT order_id, order_date, total FROM orders\nWHERE customer_id = 1\nORDER BY order_date DESC LIMIT 20\\G</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code> type: ref\n  key: orders_customer_date_idx\n rows: 81566\nExtra: Backward index scan</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX IX_Orders_Customer_Date ON dbo.Orders (CustomerId, OrderDate) INCLUDE (Total);\nGO\nSELECT TOP (20) OrderId, OrderDate, Total FROM dbo.Orders\nWHERE CustomerId = 1\nORDER BY OrderDate DESC;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 3, physical reads 0</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>CREATE INDEX orders_customer_date_idx ON orders (customer_id, order_date);\n\nEXPLAIN PLAN FOR\nSELECT order_id, order_date, total FROM orders\nWHERE customer_id = 1\nORDER BY order_date DESC FETCH FIRST 20 ROWS ONLY;\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation                      | Name                     | Rows  | Bytes | Cost (%CPU)| Time     |\n|   0 | SELECT STATEMENT               |                          |     2 |    36 |     5   (0)| 00:00:01 |\n|*  1 |  COUNT STOPKEY                 |                          |       |       |            |          |\n|   2 |   VIEW                         |                          |     2 |    36 |     5   (0)| 00:00:01 |\n|   3 |    TABLE ACCESS BY INDEX ROWID | ORDERS                   | 40234 |   903K|     5   (0)| 00:00:01 |\n|*  4 |     INDEX RANGE SCAN DESCENDING| ORDERS_CUSTOMER_DATE_IDX |     2 |       |     3   (0)| 00:00:01 |</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>CREATE INDEX orders_customer_date_idx ON orders (customer_id, order_date);\n\nEXPLAIN QUERY PLAN\nSELECT order_id, order_date, total FROM orders\nWHERE customer_id = 1\nORDER BY order_date DESC LIMIT 20;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\" data-role=\"output\"><code>`--SEARCH orders USING INDEX orders_customer_date_idx (customer_id=?)</code></pre>\n<p>An index can be read in either direction, so an ascending index serves <code>ORDER BY order_date DESC</code>. Direction only matters when the <code>ORDER BY</code> mixes ascending and descending columns; then the index has to mix them the same way, as described under <a href=\"/sql-dialects/descending-index\">descending indexes</a>.</p>\n<h3>Sort fewer or narrower rows</h3>\n<p>When no index can supply the order (the sort key is computed, or the filter is a range on a different column), make the sort smaller. Filter before sorting, and select only the columns you need: a sort carries every selected column with each row, so <code>SELECT *</code> through a sort moves far more data than three columns do.</p>\n<h3>Drop an ORDER BY nobody needs</h3>\n<p>Check that the order is used. An <code>ORDER BY</code> inside a subquery or view that the outer query re-sorts or aggregates is work for nothing, as is one feeding an application that sorts again in the grid.</p>\n<h3>When to leave it alone</h3>\n<p>Leave a sort that handles few rows, runs in memory and takes a small part of the query time. A report that sorts its whole result once is doing what it was asked. Every index added to avoid a sort is paid for on every write to the table, so add one for queries that run often, not for a sort that costs 20 milliseconds once a day.</p>","checklist_html":["Find the sort operator and note how many rows enter it and how many the query returns.","Check the sort method: in memory, top-N, or on disk.","Compare the sort's own time with the time of the step below it.","Create an index with the equality filter columns first and the ORDER BY columns after.","If no index fits, reduce the rows and columns that reach the sort.","Re-capture the plan and confirm the sort is gone or smaller."],"faqs":[{"question":"What does Using filesort mean in MySQL?","answer":"It means MySQL sorts the rows itself instead of reading them in order from an index. Despite the name it does not necessarily use a file: small sorts run in memory inside the sort buffer. It is a cost to look at when many rows are sorted."},{"question":"How do I get rid of a Sort operator?","answer":"Give the engine an index whose column order matches the query: the columns compared with = in the WHERE clause first, then the ORDER BY columns in the same order. The rows then come out of the index already sorted and the plan no longer needs to sort."},{"question":"Can an ascending index be used for ORDER BY ... DESC?","answer":"Yes. Engines read an index backwards as easily as forwards, so a single-column or same-direction ORDER BY is served by an ascending index. Only a mix such as ORDER BY a ASC, b DESC needs an index declared with the same mix."},{"question":"Why does the plan sort when there is no ORDER BY?","answer":"GROUP BY, DISTINCT, UNION, window functions and merge joins can all sort their input. The sort belongs to whichever of those sits above it in the plan. An index on the grouping or join columns can remove it in the same way."},{"question":"Is top-N heapsort a problem?","answer":"Usually not for memory, because it keeps only the rows it will return. It still reads every candidate row, so the cost is in the scan underneath. An index that provides the order lets the query stop after the first N rows."}],"plan_group":"Sorts, memory and temp space","related_slugs":["sort-and-hash-spills","full-table-scan","key-lookup"]},"source_url":"https://sqlly.app/sql-performance/expensive-sort","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/full-table-scan","corpus":"sql-performance","engine":null,"language":"en","title":"Full table scans in a query plan","description":"The plan reads a whole table to return a few rows. How to spot the scan on five engines, count the rows it throws away, and index it, with tested SQL.","body":{"slug":"full-table-scan","engines":["SQL Server","PostgreSQL","MySQL","SQLite","Oracle"],"symptoms":["Slow query","Bad index usage"],"h1":"Full table scans in a query plan","lede":"The plan reads every row of a table and keeps a handful. How to recognise the scan on each engine, measure how much it discards, add the index that turns it into a seek, and tell when the scan is the right plan.","symptom_html":"<p>A full scan reads every row of a table (or every entry of an index) and tests each one against the <code>WHERE</code> clause. It appears as <code>Seq Scan</code> in PostgreSQL, <code>Table scan</code> or <code>type: ALL</code> in MySQL, <code>Clustered Index Scan</code> or <code>Table Scan</code> in SQL Server, <code>TABLE ACCESS FULL</code> in Oracle and <code>SCAN</code> in SQLite. The scan itself is not the problem. Reading 400,000 rows to return 20 is.</p>\n<p>The examples on this page run against a small shop schema: <code>customers</code> (20,000 rows), <code>orders</code> (400,000 rows) and <code>order_items</code> (800,000 rows). Paste your own plan into the <a href=\"/tools/query-plan-viewer\">query plan viewer</a> to see the same numbers for your query.</p>","diagnosis_html":"<h3>Count what the scan reads and what it keeps</h3>\n<p>Run the query with run-time statistics, so the plan shows actual row counts next to the estimates. On PostgreSQL:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, BUFFERS)\nSELECT order_id, total FROM orders WHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Gather  (cost=1000.00..7567.43 rows=21 width=10) (actual time=0.493..6.755 rows=20.00 loops=1)\n  Workers Planned: 2\n  Workers Launched: 2\n  Buffers: shared hit=4482\n  -&gt;  Parallel Seq Scan on orders  (cost=0.00..6565.33 rows=9 width=10) (actual time=0.235..3.881 rows=6.67 loops=3)\n        Filter: (customer_id = 4242)\n        Rows Removed by Filter: 133327\n        Buffers: shared hit=4482</code></pre>\n<p>The line to read is <code>Rows Removed by Filter</code>. When it is thousands of times larger than the rows the node returns, the scan is doing work an index would skip. In a parallel plan both numbers are averages per process, so multiply by <code>loops</code>: here three processes each removed 133,327 rows, which is the whole table, to find 20.</p>\n<p>MySQL prints the same comparison with <code>EXPLAIN ANALYZE</code>. In the classic tabular <code>EXPLAIN</code>, the scan is <code>type: ALL</code> with <code>key: NULL</code>.</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN ANALYZE\nSELECT order_id, total FROM orders WHERE customer_id = 4242;\n\nEXPLAIN\nSELECT order_id, total FROM orders WHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Filter: (orders.customer_id = 4242)  (cost=40225 rows=39864) (actual time=2.05..44.4 rows=20 loops=1)\n    -&gt; Table scan on orders  (cost=40225 rows=398641) (actual time=0.101..34.9 rows=400000 loops=1)</code></pre>\n<p>On SQL Server, turn on I/O statistics and the actual plan. A table with a clustered index is scanned as a <code>Clustered Index Scan</code>, which is the same full read under another name; the filter shows up as a <code>Predicate</code> on the scan instead of a <code>Seek Predicate</code>.</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS IO ON;\nSET STATISTICS XML ON;\n\nSELECT OrderId, Total FROM dbo.Orders WHERE CustomerId = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 2579, physical reads 0</code></pre>\n<p>Oracle marks the two kinds of condition in the Predicate Information section under the plan: <code>access</code> conditions are used to find rows, <code>filter</code> conditions are tested on rows already read. A full scan has only a filter.</p>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>EXPLAIN PLAN FOR\nSELECT order_id, total FROM orders WHERE customer_id = 4242;\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation         | Name   | Rows  | Bytes | Cost (%CPU)| Time     |\n|   0 | SELECT STATEMENT  |        |    20 |   300 |   650   (1)| 00:00:01 |\n|*  1 |  TABLE ACCESS FULL| ORDERS |    20 |   300 |   650   (1)| 00:00:01 |\n\nPredicate Information (identified by operation id):\n   1 - filter(\"CUSTOMER_ID\"=4242)</code></pre>\n<p>SQLite has no row counts in its plan. <code>SCAN</code> means every row is read, <code>SEARCH</code> means an index or the primary key narrows the read.</p>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>EXPLAIN QUERY PLAN\nSELECT order_id, total FROM orders WHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\" data-role=\"output\"><code>QUERY PLAN\n`--SCAN orders</code></pre>\n<h3>An index read can discard rows too</h3>\n<p>The same waste hides behind an index when the index matches only part of the <code>WHERE</code> clause. Here the index finds every order of customer 1, and a filter then drops all but the pending ones:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nEXPLAIN (ANALYZE)\nSELECT order_id FROM orders WHERE customer_id = 1 AND status = 'pending';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Bitmap Heap Scan on orders  (cost=473.13..5580.33 rows=442 width=4) (actual time=1.054..6.091 rows=4000.00 loops=1)\n  Recheck Cond: (customer_id = 1)\n  Filter: ((status)::text = 'pending'::text)\n  Rows Removed by Filter: 36000\n  Heap Blocks: exact=4482\n  -&gt;  Bitmap Index Scan on orders_customer_idx  (cost=0.00..473.02 rows=41680 width=0) (actual time=0.717..0.718 rows=40000.00 loops=1)\n        Index Cond: (customer_id = 1)</code></pre>\n<p>The plan has an <code>Index Cond</code> (what the index was searched for) and a <code>Filter</code> (what was tested afterwards), and <code>Rows Removed by Filter</code> counts the rows that were fetched for nothing. SQL Server shows the same split as <code>Seek Predicate</code> and <code>Predicate</code>, Oracle as <code>access</code> and <code>filter</code>, and MySQL as an index lookup under a <code>Filter</code> step.</p>\n<h3>Check that the scan is not the right plan</h3>\n<p>An index only pays when the condition is selective. In the sample data 96% of orders have <code>status = 'shipped'</code>, and PostgreSQL does not use an index on <code>status</code> to find them: one pass over the table is cheaper than 384,000 separate visits.</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_status_idx ON orders (status);\n\nEXPLAIN SELECT order_id, total FROM orders WHERE status = 'shipped';\nEXPLAIN SELECT order_id, total FROM orders WHERE status = 'pending';</code></pre>\n<p>The first query keeps its <code>Seq Scan</code>; the second, which matches 1% of the table, uses the index. Before you add an index, compare the rows the scan returns with the rows in the table. If the query needs most of the table, the fix is elsewhere: return fewer rows, or see the last section.</p>","fix_html":"<h3>Index the columns the filter uses</h3>\n<p>Create an index whose leading column is the column the query filters on with <code>=</code>. Then capture the plan again and check that the scan became a seek.</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE)\nSELECT order_id, total FROM orders WHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Bitmap Heap Scan on orders  (cost=4.59..84.54 rows=21 width=10) (actual time=0.030..0.054 rows=20.00 loops=1)\n  Recheck Cond: (customer_id = 4242)\n  Heap Blocks: exact=20\n  -&gt;  Bitmap Index Scan on orders_customer_idx  (cost=0.00..4.58 rows=21 width=0) (actual time=0.023..0.023 rows=20.00 loops=1)\n        Index Cond: (customer_id = 4242)</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nEXPLAIN ANALYZE\nSELECT order_id, total FROM orders WHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Index lookup on orders using orders_customer_idx (customer_id=4242)  (cost=7 rows=20) (actual time=0.0825..0.0843 rows=20 loops=1)</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);\n\nSELECT OrderId, Total FROM dbo.Orders WHERE CustomerId = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 64, physical reads 0</code></pre>\n<p>The plan is now an <code>Index Seek</code> on the new index joined by <code>Nested Loops</code> to a <code>Key Lookup</code> that fetches <code>Total</code> from the clustered index, and logical reads fall from 2,579 to 64. The <a href=\"/sql-performance/key-lookup\">key lookup page</a> shows how to remove that second step.</p>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nEXPLAIN PLAN FOR\nSELECT order_id, total FROM orders WHERE customer_id = 4242;\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation                           | Name                | Rows  | Bytes | Cost (%CPU)| Time     |\n|   0 | SELECT STATEMENT                    |                     |    20 |   300 |    21   (0)| 00:00:01 |\n|   1 |  TABLE ACCESS BY INDEX ROWID BATCHED| ORDERS              |    20 |   300 |    21   (0)| 00:00:01 |\n|*  2 |   INDEX RANGE SCAN                  | ORDERS_CUSTOMER_IDX |    20 |       |     3   (0)| 00:00:01 |\n\nPredicate Information (identified by operation id):\n   2 - access(\"CUSTOMER_ID\"=4242)</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nEXPLAIN QUERY PLAN\nSELECT order_id, total FROM orders WHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\" data-role=\"output\"><code>QUERY PLAN\n`--SEARCH orders USING INDEX orders_customer_idx (customer_id=?)</code></pre>\n<p>On a busy production table, build the index without blocking writes: <code>CREATE INDEX CONCURRENTLY</code> on PostgreSQL, <code>WITH (ONLINE = ON)</code> on SQL Server editions that support it, <code>ONLINE</code> on Oracle. The <a href=\"/sql-dialects/create-index-concurrently\">online index build page</a> has the syntax for each engine.</p>\n<h3>Extend the index when a filter still discards rows</h3>\n<p>When the plan already uses an index but filters most of what it fetches, add the filtered column to the index key. Equality columns go first, then the range or sort column.</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_customer_status_idx ON orders (customer_id, status);\n\nEXPLAIN (ANALYZE)\nSELECT order_id FROM orders WHERE customer_id = 1 AND status = 'pending';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Bitmap Heap Scan on orders  (cost=8.95..1315.12 rows=442 width=4) (actual time=0.456..2.591 rows=4000.00 loops=1)\n  Recheck Cond: ((customer_id = 1) AND ((status)::text = 'pending'::text))\n  Heap Blocks: exact=3574\n  -&gt;  Bitmap Index Scan on orders_customer_status_idx  (cost=0.00..8.84 rows=442 width=0) (actual time=0.217..0.217 rows=4000.00 loops=1)\n        Index Cond: ((customer_id = 1) AND ((status)::text = 'pending'::text))</code></pre>\n<p>Both conditions are now in the <code>Index Cond</code> and nothing is removed by a filter. The narrower index on <code>customer_id</code> alone is now redundant and can be dropped.</p>\n<h3>Find out why an existing index is skipped</h3>\n<p>If the table already has an index on the filtered column and the plan scans anyway, the predicate does not match the index. The usual causes each have their own page: a function wrapped around the column (<a href=\"/sql-performance/non-sargable-predicates\">non-sargable predicates</a>), a type mismatch (<a href=\"/sql-performance/implicit-conversion\">implicit conversions</a>), the wrong leading column or a row estimate that makes the scan look cheaper (<a href=\"/sql-performance/index-not-used\">why the optimizer ignores your index</a>).</p>\n<h3>When to leave the scan alone</h3>\n<p>Leave it when the table is small, when the query really needs most of the rows, or when the scan feeds a hash join or an aggregate over the whole table. An index costs writes and space on every insert and update, so a scan in a nightly report is rarely worth one. Judge by rows read against rows returned and by the time the node takes, not by the word \"scan\".</p>","checklist_html":["Capture the plan with actual row counts (EXPLAIN ANALYZE, SET STATISTICS XML ON, or DBMS_XPLAN.DISPLAY_CURSOR).","Find the scan and compare the rows it reads with the rows it returns.","Compare the rows returned with the size of the table: above a few percent, the scan may be the right plan.","Check for an existing index on the filtered column; if there is one, find out why the predicate does not match it.","Create an index led by the equality columns of the WHERE clause.","Re-capture the plan and confirm the scan became a seek and the discarded rows are gone.","Drop any index the new one made redundant."],"faqs":[{"question":"Is a full table scan always bad?","answer":"No. It is the cheapest way to read most of a table, and the only sensible way to read a small one. It is a problem when the scan reads many times more rows than the query returns, and the query runs often enough or long enough to matter."},{"question":"Why does SQL Server show a Clustered Index Scan instead of a Table Scan?","answer":"A table with a clustered index is stored in that index, so reading the whole table is a scan of the clustered index. Table Scan appears only for heaps, tables without a clustered index. Both read every row."},{"question":"The index exists. Why does the plan still scan the table?","answer":"Either the predicate cannot use the index (a function or a type conversion on the column, a leading wildcard, the wrong leading column) or the optimizer estimates that the query returns too large a share of the table for the index to be cheaper. Compare estimated and actual rows on the scan to tell the two apart."},{"question":"What does Rows Removed by Filter mean in PostgreSQL?","answer":"It is the number of rows the node read and then discarded because they failed the Filter condition. In a parallel plan it is an average per process, so multiply by the loops value. A large number next to a small row count means an index on the filtered column would avoid most of the work."},{"question":"Should I add every index the plan seems to want?","answer":"No. Each index slows down inserts, updates and deletes on the table and takes space. Add the index for queries that run often or block users, prefer one composite index that serves several queries over several single-column ones, and check after a week that the index is used."}],"plan_group":"Indexes and access paths","related_slugs":["missing-index","key-lookup","index-not-used"]},"source_url":"https://sqlly.app/sql-performance/full-table-scan","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/high-cpu","corpus":"sql-performance","engine":null,"language":"en","title":"Finding what burns CPU on a database server","description":"The database server runs hot on CPU. Find the statements responsible with each engine's statement history, then fix the scans, sorts and functions that burn CPU.","body":{"slug":"high-cpu","engines":["SQL Server","PostgreSQL","MySQL","Oracle"],"symptoms":["High CPU","Slow query"],"h1":"Finding what burns CPU on a database server","lede":"CPU pegged on the database box. CPU cost follows logical reads and row-by-row work, so the statement history names the culprits: how to rank them on SQL Server, PostgreSQL, MySQL and Oracle, then fix the usual CPU shapes.","symptom_html":"<p>The database server's CPU is at 90% and the monitoring does not say why. Databases burn CPU on three things: <em>logical reads</em> (every page touched is work), <em>sorting and hashing</em>, and <em>per-row functions</em> or recompiles. The statement history ranks all three, because CPU time is recorded per query.</p>","diagnosis_html":"<h3>SQL Server: the plan cache and the schedulers</h3>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT TOP 10\nqs.total_worker_time / 1000 AS cpu_ms,\nqs.execution_count,\nqs.total_worker_time / qs.execution_count / 1000 AS cpu_ms_per_run,\nSUBSTRING(st.text, (qs.statement_start_offset / 2) + 1,\n((CASE qs.statement_end_offset\n WHEN -1 THEN DATALENGTH(st.text)\n ELSE qs.statement_end_offset\nEND - qs.statement_start_offset) / 2) + 1) AS sql_text\nFROM sys.dm_exec_query_stats AS qs\nCROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st\nORDER BY qs.total_worker_time DESC;</code></pre>\n<p><code>cpu_ms_per_run</code> separates the query called 10 times an hour that burns 8 seconds of CPU each from one called a million times at 3 ms. Both need fixing; differently. Confirm the pressure is real work with <code>sys.dm_os_schedulers</code> (<code>runnable_tasks_count</code> persistently above zero on many schedulers means CPU starvation, not a runaway query).</p>\n<h3>PostgreSQL: pg_stat_statements</h3>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SELECT calls, round(total_exec_time::numeric) AS total_ms,\nround(mean_exec_time::numeric, 1) AS mean_ms,\nshared_blks_hit + shared_blks_read AS blocks,\nleft(query, 80) AS query\nFROM pg_stat_statements\nORDER BY total_exec_time DESC\nLIMIT 10;</code></pre>\n<p>The <code>blocks</code> column is the tell: high blocks per call means the CPU is chasing pages, and an index fixes it; low blocks with high mean time means the CPU is spent in functions, regexes or sorting inside the query itself.</p>\n<h3>MySQL: the digest table</h3>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>SELECT LEFT(DIGEST_TEXT, 80) AS query, COUNT_STAR,\nround(SUM_TIMER_WAIT / 1e12, 1) AS total_seconds,\nSUM_ROWS_EXAMINED, SUM_ROWS_SENT,\nSUM_NO_INDEX_USED AS runs_without_index\nFROM performance_schema.events_statements_summary_by_digest\nORDER BY SUM_ROWS_EXAMINED DESC\nLIMIT 10;</code></pre>\n<p>MySQL spends most of its CPU reading and filtering rows, so rank by rows examined: a digest that examines millions of rows to send a few hundred is where the cores go. <code>SUM_NO_INDEX_USED</code> counts executions that did a full scan, not rows. <code>sys.statements_with_full_table_scans</code> lists the same offenders in plainer words.</p>\n<h3>Oracle: ASH and v$sqlstats</h3>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>SELECT sql_id, COUNT(*) AS cpu_samples\nFROM v$active_session_history\nWHERE session_state = 'ON CPU'\nAND sample_time &gt; SYSTIMESTAMP - INTERVAL '30' MINUTE\nGROUP BY sql_id\nORDER BY cpu_samples DESC\nFETCH FIRST 10 ROWS ONLY;</code></pre>\n<p>Each ON CPU sample is roughly a second of CPU (or of waiting in the OS run queue for one), so this is the CPU budget by query. ASH needs the Diagnostics Pack; without it, order <code>v$sqlstats</code> by <code>cpu_time</code> and compare two snapshots taken a few minutes apart.</p>","fix_html":"<p><strong>Kill the scans first.</strong> The query with the most logical reads per execution is the CPU leader almost everywhere; add the index its predicate wants and CPU falls with it. The <a href=\"/sql-performance/slow-query\">slow query guide's</a> plan method applies unchanged. The index for a hot filter by customer and date range, per engine:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX idx_orders_customer_created\nON dbo.Orders (CustomerId, CreatedAt);</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX CONCURRENTLY idx_orders_customer_created\nON orders (customer_id, created_at);</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>ALTER TABLE orders\nADD INDEX idx_orders_customer_created (customer_id, created_at);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>CREATE INDEX idx_orders_customer_created\nON orders (customer_id, created_at);</code></pre>\n<p><strong>Then kill the row-by-row work.</strong> Functions on columns in WHERE clauses, per-row scalar subqueries, application-side loops re-running a prepared statement millions of times (visible as a huge <code>execution_count</code>/<code>calls</code>) - each is CPU the engine cannot amortize. A set-based rewrite or a bigger batch turns a million cheap CPU burns into one cheap pass.</p>\n<p><strong>Watch for compile churn.</strong> Ad-hoc SQL with literal values gets compiled on every run; on SQL Server it fills the plan cache with single-use plans (<code>usecounts = 1</code> in <code>sys.dm_exec_cached_plans</code>) and burns CPU compiling. The app switching to bind parameters fixes it; database-level <code>PARAMETERIZATION FORCED</code> is the stopgap. PostgreSQL plans every unprepared statement afresh, and pg_stat_statements folds the literals together, so the cost shows up as planning time: set <code>pg_stat_statements.track_planning = on</code> and compare <code>total_plan_time</code> with <code>total_exec_time</code>.</p>\n<h3>When the burn is not a query</h3>\n<p>When the statement history is clean but the box still runs hot, the CPU belongs to something outside the engine: backup agents, monitoring, antivirus, or a second instance sharing the host. The engine's accounting only tallies what the engine itself spends, so a clean top-ten list clears the database and points the search at the OS.</p>\n<p><strong>Only then resize.</strong> If the top statements are fixed and CPU still peaks at business hours, more cores may be right - but a server at 100% CPU serving an unindexed query stays at 100% CPU on bigger hardware too. Capture the plans of the remaining leaders with the method in the <a href=\"/sql-performance/slow-query\">slow query guide</a>, and paste them into the <a href=\"/tools/query-plan-viewer\">query plan viewer</a> so the expensive operators are visible at a glance.</p>","checklist_html":["Rank statements by total CPU from the engine's statement history (queries above).","Split the list by calls: one heavy query vs one query called a million times.","For the heavy one, capture the plan and find the scans and spills.","For the chatty one, find the call site in the app and batch or cache it.","Add the index the top scan wants; re-measure CPU over the same period next day.","Check for per-row functions in WHERE/SELECT and rewrite them set-based.","Only consider resizing after the top three offenders are fixed."],"faqs":[{"question":"How do I tell CPU pressure from other load?","answer":"Count the sessions that want CPU against the cores you have. SQL Server: runnable_tasks_count in sys.dm_os_schedulers, plus a high share of signal_wait_time_ms in sys.dm_os_wait_stats. PostgreSQL: active backends in pg_stat_activity whose wait_event is NULL are running on CPU (there is no CPU wait event), compared with the OS load average. MySQL: the Threads_running status counter. Oracle: ON CPU sessions in v$session. If more sessions want CPU than there are cores, CPU is the bottleneck; if they wait on I/O or locks, the CPU spike is a symptom, not the cause."},{"question":"Can a query burn CPU without reading a lot of rows?","answer":"Yes - CPU goes to parsing, compiling, functions, regexp and sorting. A query over a 20-row table called a million times can be the top CPU consumer while the 'big' report never registers. That is why the ranking splits by execution count before you optimize anything."},{"question":"Does more RAM reduce CPU?","answer":"Often, indirectly: if pages are read from disk repeatedly, the CPU pays for every read. Fixing the working set (buffer pool, shared_buffers) lowers both I/O and the CPU that services it. But a plan that scans 10 million rows to return 50 stays expensive at any memory size."},{"question":"Should I limit parallelism to reduce CPU load?","answer":"Only when the evidence says so: CXPACKET-dominated waits on SQL Server, or many parallel workers in pg_stat_activity (backend_type = 'parallel worker') on PostgreSQL, can mean parallel plans are amplifying load. On SQL Server the usual first change is raising cost threshold for parallelism from its default of 5, not cutting MAXDOP to 1. Lowering parallelism reduces per-query CPU but raises latency - it is a trade to make with the plan in hand, not a first move."},{"question":"What if CPU is high but the database shows idle sessions?","answer":"Then the CPU is not the database's: check the OS (backup agents, monitoring, antivirus, other processes on the box). The database's own accounting - the queries here - only tallies what the database itself spends."}],"plan_group":null,"related_slugs":[]},"source_url":"https://sqlly.app/sql-performance/high-cpu","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/implicit-conversion","corpus":"sql-performance","engine":null,"language":"en","title":"Implicit conversions and type mismatches","description":"The value and the column have different types, the engine converts the column, and the index is skipped. How to spot CONVERT_IMPLICIT and fix the types.","body":{"slug":"implicit-conversion","engines":["SQL Server","MySQL","Oracle","PostgreSQL"],"symptoms":["Bad index usage","Slow query"],"h1":"Implicit conversions and type mismatches","lede":"A comparison between two different types makes the engine convert one side. When it converts the column, the index on that column cannot be searched. How each engine shows the conversion in the plan and how to make the types match.","symptom_html":"<p>When a query compares a column with a value of another type, the engine converts one side so the two can be compared. Each engine has fixed rules for which side changes. If the value is converted, nothing happens to the plan. If the column is converted, the query has become <code>function(column) = value</code>, and an index on the column can no longer be searched: the same problem as a <a href=\"/sql-performance/non-sargable-predicates\">non-sargable predicate</a>, except that nobody wrote the function.</p>\n<p>SQL Server shows it as <code>CONVERT_IMPLICIT</code> in the predicate and adds a warning to the plan. Oracle shows <code>TO_NUMBER</code> or <code>INTERNAL_FUNCTION</code> in the predicate section, PostgreSQL shows a cast on the column, and MySQL shows a full scan with the index listed under <code>possible_keys</code> but not used. The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> reports the conversion and the column it hit. The examples use a shop schema with 20,000 customers and 400,000 orders.</p>","diagnosis_html":"<h3>SQL Server: CONVERT_IMPLICIT and the plan warning</h3>\n<p>The usual case is a <code>varchar</code> column compared with an <code>nvarchar</code> value. <code>nvarchar</code> has the higher type precedence, so the column is converted:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX IX_Orders_Reference ON dbo.Orders (Reference);\nGO\nSET STATISTICS IO ON;\nSET STATISTICS XML ON;\nGO\nDECLARE @ref nvarchar(20) = N'R4242';\nSELECT OrderId FROM dbo.Orders WHERE Reference = @ref;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 1039, physical reads 0</code></pre>\n<p>The plan carries a <code>PlanAffectingConvert</code> warning, drawn as a yellow triangle on the root operator in Management Studio, and the predicate reads <code>CONVERT_IMPLICIT(nvarchar(20),[Reference],0)=[@ref]</code>. The same query with a <code>varchar</code> variable:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>DECLARE @ref varchar(20) = 'R4242';\nSELECT OrderId FROM dbo.Orders WHERE Reference = @ref;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 3, physical reads 0</code></pre>\n<p>How much the conversion costs depends on the column's collation. With a SQL Server collation (the names that start with <code>SQL_</code>), as here, the index is scanned from end to end. With a Windows collation the optimizer can still seek a range, and the cost is smaller.</p>\n<p>A number compared with a string goes the other way. <code>int</code> has precedence over <code>varchar</code>, so in <code>CustomerId = '4242'</code> the literal is converted and the index is still searched:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);\nGO\nSELECT OrderId FROM dbo.Orders WHERE CustomerId = '4242';</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 4, physical reads 0</code></pre>\n<h3>MySQL: a string column compared with a number</h3>\n<p>MySQL compares a string column with a number by converting every string to a number, which rules out the index. The plan lists the index under <code>possible_keys</code> and uses none:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>CREATE TABLE customer_notes (\n    note_id int PRIMARY KEY,\n    customer_ref varchar(20) NOT NULL,\n    note varchar(100) NOT NULL,\n    KEY customer_notes_ref_idx (customer_ref)\n);\nINSERT INTO customer_notes\nSELECT customer_id, customer_id, 'call back' FROM customers;\nANALYZE TABLE customer_notes;\n\nEXPLAIN SELECT note FROM customer_notes WHERE customer_ref = 4242\\G\n\nEXPLAIN SELECT note FROM customer_notes WHERE customer_ref = '4242'\\G</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>         type: ALL\npossible_keys: customer_notes_ref_idx\n          key: NULL\n         rows: 20405\n        Extra: Using where\n         type: ref\npossible_keys: customer_notes_ref_idx\n          key: customer_notes_ref_idx\n         rows: 1\n        Extra: NULL</code></pre>\n<h3>Oracle: TO_NUMBER in the predicate section</h3>\n<p>Oracle also converts the string column when it meets a number. The predicate section under the plan shows the function it added:</p>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>CREATE TABLE customer_notes AS\nSELECT customer_id AS note_id, TO_CHAR(customer_id) AS customer_ref, 'call back' AS note\nFROM customers;\nCREATE INDEX customer_notes_ref_idx ON customer_notes (customer_ref);\n\nEXPLAIN PLAN FOR\nSELECT note FROM customer_notes WHERE customer_ref = 4242;\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation         | Name           | Rows  | Bytes | Cost (%CPU)| Time     |\n|   0 | SELECT STATEMENT  |                |     1 |    16 |    23   (0)| 00:00:01 |\n|*  1 |  TABLE ACCESS FULL| CUSTOMER_NOTES |     1 |    16 |    23   (0)| 00:00:01 |\n   1 - filter(TO_NUMBER(\"CUSTOMER_REF\")=4242)</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>EXPLAIN PLAN FOR\nSELECT note FROM customer_notes WHERE customer_ref = '4242';\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation                           | Name                   | Rows  | Bytes | Cost (%CPU)| Time     |\n|   0 | SELECT STATEMENT                    |                        |     1 |    16 |     2   (0)| 00:00:01 |\n|   1 |  TABLE ACCESS BY INDEX ROWID BATCHED| CUSTOMER_NOTES         |     1 |    16 |     2   (0)| 00:00:01 |\n|*  2 |   INDEX RANGE SCAN                  | CUSTOMER_NOTES_REF_IDX |     1 |       |     1   (0)| 00:00:01 |\n   2 - access(\"CUSTOMER_REF\"='4242')</code></pre>\n<h3>PostgreSQL: a cast on the column in the filter</h3>\n<p>PostgreSQL refuses most mixed comparisons outright (a <code>varchar</code> column against an integer is an error), so the problem is rarer. It does appear between numeric types: an <code>integer</code> column compared with a <code>numeric</code> value is converted to <code>numeric</code>.</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nEXPLAIN SELECT order_id FROM orders WHERE customer_id = 4242.0;\n\nEXPLAIN SELECT order_id FROM orders WHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>  -&gt;  Parallel Seq Scan on orders  (cost=0.00..6982.00 rows=833 width=4)\n        Filter: ((customer_id)::numeric = 4242.0)\nBitmap Heap Scan on orders  (cost=4.58..80.82 rows=20 width=4)\n  Recheck Cond: (customer_id = 4242)\n  -&gt;  Bitmap Index Scan on orders_customer_idx  (cost=0.00..4.57 rows=20 width=0)\n        Index Cond: (customer_id = 4242)</code></pre>\n<p>This reaches production through parameters: a driver or ORM that binds a decimal type for a column that is an integer.</p>\n<h3>Joins between columns of different types</h3>\n<p>The same conversion happens when two joined columns were declared with different types. The side that gets converted cannot use its index for the join, so the join can only be driven from that side:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN FORMAT=TREE\nSELECT c.email, n.note\nFROM customers AS c\nJOIN customer_notes AS n ON n.customer_ref = c.customer_id\nWHERE c.country = 'DE';</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Nested loop inner join  (cost=9206 rows=2041)\n    -&gt; Table scan on n  (cost=2065 rows=20405)\n    -&gt; Filter: ((c.country = 'DE') and (cast(n.customer_ref as double) = cast(c.customer_id as double)))  (cost=0.25 rows=0.1)\n        -&gt; Single-row index lookup on c using PRIMARY (customer_id=n.customer_ref)  (cost=0.25 rows=1)</code></pre>","fix_html":"<h3>Send the value in the column's type</h3>\n<p>The cheapest fix is on the calling side. Quote the literal, or declare the parameter with the column's type. In application code this means setting the parameter type explicitly: client libraries commonly send every string as <code>nvarchar</code> to SQL Server unless told otherwise, which is how a <code>varchar</code> column ends up converted on every call.</p>\n<h3>Cast the value, not the column</h3>\n<p>When you cannot control the type that arrives, convert the value in the query. A conversion on the value side runs once:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>DECLARE @ref nvarchar(20) = N'R4242';\nSELECT OrderId FROM dbo.Orders WHERE Reference = CAST(@ref AS varchar(20));</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 3, physical reads 0</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN SELECT note FROM customer_notes WHERE customer_ref = CAST(4242 AS CHAR)\\G</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code> type: ref\n  key: customer_notes_ref_idx\n rows: 1\nExtra: NULL</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN SELECT order_id FROM orders WHERE customer_id = CAST(4242.0 AS integer);</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Bitmap Heap Scan on orders  (cost=4.58..80.82 rows=20 width=4)\n  Recheck Cond: (customer_id = 4242)\n  -&gt;  Bitmap Index Scan on orders_customer_idx  (cost=0.00..4.57 rows=20 width=0)\n        Index Cond: (customer_id = 4242)</code></pre>\n<h3>Change the column type when the column is wrong</h3>\n<p>If a column holds numbers and is declared as a string, or two columns that are always joined have different types, fix the schema. For the join above, make the referencing column an integer like the key it points to:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>ALTER TABLE customer_notes MODIFY customer_ref int NOT NULL;\nANALYZE TABLE customer_notes;\n\nEXPLAIN FORMAT=TREE\nSELECT c.email, n.note\nFROM customers AS c\nJOIN customer_notes AS n ON n.customer_ref = c.customer_id\nWHERE c.country = 'DE';</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Nested loop inner join  (cost=2672 rows=1962)\n    -&gt; Filter: (c.country = 'DE')  (cost=1986 rows=1962)\n        -&gt; Table scan on c  (cost=1986 rows=19616)\n    -&gt; Index lookup on n using customer_notes_ref_idx (customer_ref=c.customer_id)  (cost=0.25 rows=1)</code></pre>\n<p>Changing a column type rewrites the table on most engines and takes locks; plan it like any other schema change. The <a href=\"/sql-dialects/implicit-cast-comparison\">implicit cast comparison page</a> lists the conversion rules per engine.</p>\n<h3>When to leave it alone</h3>\n<p>Leave it when the conversion is on the value side, when the table is small, or when the converted column is not the one the query needs an index for. A <code>CONVERT_IMPLICIT</code> in the select list changes nothing about how rows are found. SQL Server's warning also fires for conversions that only affect the row estimate; check whether the plan actually scans before you change anything.</p>","checklist_html":["Look for CONVERT_IMPLICIT (SQL Server), TO_NUMBER or INTERNAL_FUNCTION (Oracle), or a cast on the column (PostgreSQL).","In MySQL, look for an index listed in possible_keys with key empty.","Compare the declared type of the column with the type of the literal or parameter.","Fix the calling side first: quote the literal or set the parameter type.","Otherwise cast the value in the query, never the column.","For joins, make both columns the same type.","Re-capture the plan and confirm the index is searched."],"faqs":[{"question":"What is CONVERT_IMPLICIT in a SQL Server plan?","answer":"It is a type conversion SQL Server added because the two sides of a comparison had different types. When it wraps a column, as in CONVERT_IMPLICIT(nvarchar(20),[Reference],0), every row's value has to be converted before it can be compared, and an index on that column is scanned instead of searched."},{"question":"Which side gets converted?","answer":"It depends on the engine. SQL Server converts the side with the lower type precedence, so varchar becomes nvarchar and strings become numbers. MySQL and Oracle convert a string column to a number when it is compared with a number. PostgreSQL converts integer to numeric and rejects most string-to-number comparisons with an error."},{"question":"Why does my ORM cause implicit conversions?","answer":"Because of how it binds parameters. Client libraries often send strings as Unicode text and may pick a numeric type that is wider than the column. Against a varchar or integer column that forces a conversion of the column. Setting the parameter type to match the column removes it."},{"question":"Does an implicit conversion always cause a scan?","answer":"No. If the value is converted, the index works normally. Even when the column is converted, SQL Server can still seek for some combinations, such as varchar to nvarchar under a Windows collation. The plan tells you: look at whether the index is searched or scanned."},{"question":"How do I find type mismatches between joined columns?","answer":"Compare the declared types of both sides of each join condition in the catalog: information_schema.columns on most engines. Columns that are joined should have the same type, length and, for strings, the same collation."}],"plan_group":"Indexes and access paths","related_slugs":["non-sargable-predicates","full-table-scan","index-not-used"]},"source_url":"https://sqlly.app/sql-performance/implicit-conversion","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/index-merge","corpus":"sql-performance","engine":null,"language":"en","title":"Index merge and BitmapAnd plans","description":"The plan reads two single-column indexes and combines the results. When one composite index is the better answer in MySQL and PostgreSQL, and when it is not.","body":{"slug":"index-merge","engines":["MySQL","PostgreSQL"],"symptoms":["Bad index usage","Slow query"],"h1":"Index merge and BitmapAnd plans","lede":"The plan reads two single-column indexes and intersects or unites what they return. How MySQL index_merge and PostgreSQL BitmapAnd and BitmapOr show up, why an intersection usually means a composite index is missing, and why a union is usually fine.","symptom_html":"<p>When a query filters on two columns and each has its own index, the engine can read both indexes and combine the row lists. MySQL calls this <code>index_merge</code> and names the method in the <code>Extra</code> column: <code>Using intersect(...)</code> for <code>AND</code>, <code>Using union(...)</code> or <code>Using sort_union(...)</code> for <code>OR</code>. PostgreSQL shows a <code>BitmapAnd</code> or <code>BitmapOr</code> node over two <code>Bitmap Index Scan</code> nodes.</p>\n<p>An intersection reads every matching entry from both indexes to keep the few that are in both. One index on both columns would go straight to those rows, which is why the <a href=\"/tools/query-plan-viewer\">query plan viewer</a> flags it. A union is different: no single ordinary index can answer an <code>OR</code> across two columns, and the merge is often the best plan there is. The examples use a shop schema with 400,000 orders.</p>","diagnosis_html":"<h3>MySQL: type index_merge</h3>\n<p>With separate indexes on <code>customer_id</code> and <code>status</code>, a filter on both columns intersects them:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\nCREATE INDEX orders_status_idx ON orders (status);\n\nEXPLAIN\nSELECT order_id, total FROM orders WHERE customer_id = 1 AND status = 'cancelled'\\G</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code> type: index_merge\n  key: orders_status_idx,orders_customer_idx\n rows: 4460\nExtra: Using intersect(orders_status_idx,orders_customer_idx); Using where</code></pre>\n<p><code>EXPLAIN ANALYZE</code> shows what the intersection costs: how many entries each index returned against how many rows survived.</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN ANALYZE\nSELECT order_id, total FROM orders WHERE customer_id = 1 AND status = 'cancelled';</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Filter: ((orders.`status` = 'cancelled') and (orders.customer_id = 1))  (cost=1536 rows=4460) (actual time=0.0511..11.3 rows=4000 loops=1)\n    -&gt; Intersect rows sorted by row ID  (cost=1536 rows=4461) (actual time=0.0465..11 rows=4000 loops=1)\n        -&gt; Index range scan on orders using orders_status_idx over (status = 'cancelled')  (cost=0.0105..236 rows=22534) (actual time=0.0203..1.52 rows=12000 loops=1)\n        -&gt; Index range scan on orders using orders_customer_idx over (customer_id = 1)  (cost=988e-6..78 rows=78912) (actual time=0.0151..5.05 rows=39998 loops=1)</code></pre>\n<p>The two index scans return about 12,000 and 40,000 entries to produce 4,000 rows. MariaDB prints the same <code>index_merge</code> type and <code>Using intersect(...)</code> text for this query.</p>\n<h3>PostgreSQL: BitmapAnd</h3>\n<p>PostgreSQL builds a bitmap of matching row locations from each index and combines the bitmaps before it visits the table:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\nCREATE INDEX orders_status_idx ON orders (status);\n\nEXPLAIN (ANALYZE, BUFFERS)\nSELECT order_id, total FROM orders\nWHERE customer_id BETWEEN 2 AND 600 AND status = 'cancelled';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Bitmap Heap Scan on orders  (cost=287.93..1305.93 rows=327 width=10) (actual time=0.725..0.937 rows=240.00 loops=1)\n  Recheck Cond: (((status)::text = 'cancelled'::text) AND (customer_id &gt;= 2) AND (customer_id &lt;= 600))\n  Heap Blocks: exact=240\n  -&gt;  BitmapAnd  (cost=287.93..287.93 rows=327 width=0) (actual time=0.690..0.690 rows=0.00 loops=1)\n        -&gt;  Bitmap Index Scan on orders_status_idx  (cost=0.00..135.32 rows=12120 width=0) (actual time=0.303..0.303 rows=12000.00 loops=1)\n              Index Cond: ((status)::text = 'cancelled'::text)\n        -&gt;  Bitmap Index Scan on orders_customer_idx  (cost=0.00..152.19 rows=10777 width=0) (actual time=0.252..0.252 rows=10800.00 loops=1)\n              Index Cond: ((customer_id &gt;= 2) AND (customer_id &lt;= 600))</code></pre>\n<p>Read the <code>rows</code> of each <code>Bitmap Index Scan</code> against the <code>rows</code> of the <code>Bitmap Heap Scan</code> on top: 12,000 and 10,800 index entries for 240 rows. The <code>BitmapAnd</code> node itself always reports <code>rows=0</code>; a bitmap has no row count.</p>\n<h3>OR produces a union</h3>\n<p>The same two indexes serve an <code>OR</code>, and here each index contributes rows the other cannot find:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN\nSELECT order_id, total FROM orders WHERE customer_id = 4242 OR status = 'pending'\\G</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code> type: index_merge\n  key: orders_customer_idx,orders_status_idx\n rows: 4020\nExtra: Using union(orders_customer_idx,orders_status_idx); Using where</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, BUFFERS)\nSELECT order_id, total FROM orders WHERE customer_id = 4242 OR status = 'pending';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Bitmap Heap Scan on orders  (cost=53.44..4675.69 rows=4074 width=10) (actual time=0.323..1.810 rows=4020.00 loops=1)\n  Recheck Cond: ((customer_id = 4242) OR ((status)::text = 'pending'::text))\n  Heap Blocks: exact=2572\n  -&gt;  BitmapOr  (cost=53.44..53.44 rows=4074 width=0) (actual time=0.149..0.149 rows=0.00 loops=1)\n        -&gt;  Bitmap Index Scan on orders_customer_idx  (cost=0.00..4.58 rows=21 width=0) (actual time=0.010..0.010 rows=20.00 loops=1)\n              Index Cond: (customer_id = 4242)\n        -&gt;  Bitmap Index Scan on orders_status_idx  (cost=0.00..46.82 rows=4053 width=0) (actual time=0.138..0.139 rows=4000.00 loops=1)\n              Index Cond: ((status)::text = 'pending'::text)</code></pre>","fix_html":"<h3>Replace an intersection with a composite index</h3>\n<p>Create one index with both columns. Put the column compared with <code>=</code> first and the range column after it:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>CREATE INDEX orders_customer_status_idx ON orders (customer_id, status);\n\nEXPLAIN ANALYZE\nSELECT order_id, total FROM orders WHERE customer_id = 1 AND status = 'cancelled';</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Index lookup on orders using orders_customer_status_idx (customer_id=1, status='cancelled')  (cost=1400 rows=4000) (actual time=0.295..3.41 rows=4000 loops=1)</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_status_customer_idx ON orders (status, customer_id);\n\nEXPLAIN (ANALYZE, BUFFERS)\nSELECT order_id, total FROM orders\nWHERE customer_id BETWEEN 2 AND 600 AND status = 'cancelled';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Index Scan using orders_status_customer_idx on orders  (cost=0.42..644.05 rows=327 width=10) (actual time=0.016..0.231 rows=240.00 loops=1)\n  Index Cond: (((status)::text = 'cancelled'::text) AND (customer_id &gt;= 2) AND (customer_id &lt;= 600))\n  Buffers: shared hit=240 read=3</code></pre>\n<p>The index now returns exactly the rows the query keeps. Once the composite index exists, a single-column index on its leading column is redundant, because the composite index serves the same lookups. The <a href=\"/sql-snippets/redundant-prefix-indexes\">redundant prefix index snippet</a> finds those.</p>\n<h3>Leave a union alone, or split the query</h3>\n<p>For <code>OR</code> across two columns the merge is usually right. If the plan falls back to a full scan instead, write the two halves as separate queries so each uses its own index. <code>UNION</code> removes the rows that match both conditions:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN FORMAT=TREE\nSELECT order_id, total FROM orders WHERE customer_id = 4242\nUNION\nSELECT order_id, total FROM orders WHERE status = 'pending';</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Table scan on &lt;union temporary&gt;  (cost=1809..1862 rows=4020)\n    -&gt; Union materialize with deduplication  (cost=1809..1809 rows=4020)\n        -&gt; Index lookup on orders using orders_customer_idx (customer_id=4242)  (cost=7 rows=20)\n        -&gt; Index lookup on orders using orders_status_idx (status='pending')  (cost=1400 rows=4000)</code></pre>\n<h3>MySQL: turn the intersection off for one session</h3>\n<p>To compare the plan without the merge before you build an index, switch the method off for your session:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>DROP INDEX orders_customer_status_idx ON orders;\nSET SESSION optimizer_switch = 'index_merge_intersection=off';\n\nEXPLAIN\nSELECT order_id, total FROM orders WHERE customer_id = 1 AND status = 'cancelled'\\G\n\nSET SESSION optimizer_switch = 'index_merge_intersection=default';</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code> type: ref\n  key: orders_status_idx\n rows: 22534\nExtra: Using where</code></pre>\n<h3>When to leave it alone</h3>\n<p>Leave an intersection when the query is rare, or when the two columns are filtered in many different combinations and one composite index per combination would be too many indexes on a table that takes writes. Leave a union when it reads few rows. Build the composite index when the same pair of columns is filtered together all day and each single index returns many times more entries than the query keeps.</p>","checklist_html":["Find index_merge in the type column (MySQL) or BitmapAnd / BitmapOr (PostgreSQL).","Note whether it is an intersection (AND) or a union (OR).","For an intersection, compare the entries each index returns with the rows the query keeps.","Create a composite index: equality columns first, the range column last.","Re-capture the plan and confirm a single index read.","Drop a single-column index that the composite index now makes redundant."],"faqs":[{"question":"Is index merge bad?","answer":"Not by itself. An intersection means the engine read two indexes to do the work one composite index would do, so it is a hint that an index is missing. A union for an OR condition is often the best available plan."},{"question":"What does Using intersect mean in MySQL EXPLAIN?","answer":"MySQL scanned the indexes named in the brackets, kept the row ids that appear in all of them, and then read those rows. It appears for AND conditions when each column has its own index and no index contains them together."},{"question":"Why does BitmapAnd show rows=0 in PostgreSQL?","answer":"A BitmapAnd or BitmapOr node produces a bitmap of row locations, not rows, so EXPLAIN ANALYZE reports zero for it. Read the row counts on the Bitmap Index Scan nodes below it and on the Bitmap Heap Scan above it."},{"question":"Which column goes first in the composite index?","answer":"Columns compared with = go first, and a column filtered by a range goes after them. With two equality columns either order serves this query, so lead with the column that other queries filter on alone."},{"question":"Can I keep the single-column indexes?","answer":"Keep the one that is not the leading column of the new composite index if other queries filter on that column alone. The single-column index on the leading column duplicates the composite index and only adds write cost."}],"plan_group":"Indexes and access paths","related_slugs":["full-table-scan","key-lookup","index-not-used"]},"source_url":"https://sqlly.app/sql-performance/index-merge","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/index-not-used","corpus":"sql-performance","engine":null,"language":"en","title":"Why the optimizer ignores your index","description":"An index exists but the plan ignores it: the usual causes - column order, functions, implicit conversions, wildcards and stale stats - and how to prove each.","body":{"slug":"index-not-used","engines":["SQL Server","PostgreSQL","MySQL","SQLite","Oracle"],"symptoms":["Bad index usage","Slow query"],"h1":"Why the optimizer ignores your index","lede":"The index is there but the plan scans the table anyway. The usual reasons: wrong leading column, a function or implicit conversion on the predicate, a leading-wildcard LIKE, low selectivity, or statistics that make scanning look cheaper.","symptom_html":"<p>You built the index, the plan still scans the table. The optimizer is not being stubborn - an index is only usable when the predicate matches its shape and using it is actually cheaper. Each cause below leaves a specific fingerprint in the plan.</p>","diagnosis_html":"<h3>The predicate does not match the leading column</h3>\n<p>Composite indexes work left to right. An index on <code>(customer_id, status)</code> serves predicates on <code>customer_id</code> or <code>customer_id AND status</code>, but a predicate on <code>status</code> alone cannot seek into it, and the plan shows a scan. The fix is an index led by <code>status</code>. Check this first; it is the most common cause. The partial exception is a skip scan, which probes the index once per distinct leading value: Oracle, MySQL 8.0.13+, SQLite (once ANALYZE has gathered statistics) and PostgreSQL 18 can do it when the leading column has very few distinct values. A skip scan is cheaper than a full scan but still slower than an index with the right leading column.</p>\n<h3>A function or cast sits on the column</h3>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>WHERE DATE(created_at) = '2026-05-01'      -- function on the column: no seek\nWHERE created_at &gt;= '2026-05-01'\nAND created_at &lt; '2026-05-02'            -- same meaning: seeks</code></pre>\n<p>The same happens with type mismatches. On SQL Server, a <code>varchar</code> column compared with an <code>nvarchar</code> parameter (what most drivers send for strings by default) gets converted to nvarchar row by row; with a SQL_ collation that turns the seek into a scan, and the plan shows a <code>CONVERT_IMPLICIT</code> warning. On MySQL, a string column compared with a number (<code>WHERE phone = 5551234</code>) is converted per row and cannot use its index; the reverse, a numeric column compared with a string literal, is fine. Move the function to the other side of the comparison and send parameters in the column's type.</p>\n<h3>The LIKE starts with a wildcard</h3>\n<p><code>LIKE '%smith'</code> cannot use a B-tree seek because the index is ordered left to right. <code>LIKE 'smith%'</code> seeks fine. Infix and suffix search need a full-text index, a trigram index (PostgreSQL <code>pg_trgm</code> with a GIN index serves <code>LIKE '%smith%'</code> directly), or for suffixes, an index on the reversed string. Two engine traps for prefix LIKE: PostgreSQL only uses a plain B-tree index for <code>LIKE 'smith%'</code> when the database collation is C, so otherwise create the index with <code>text_pattern_ops</code>; and SQLite's case-insensitive LIKE needs an index declared <code>COLLATE NOCASE</code>.</p>\n<h3>Scanning really is cheaper</h3>\n<p>If the predicate matches most of the table, seeking per row costs more than one sequential pass - the optimizer is right. Check the estimated rows of the scan against the table size. If the estimate is honest, the fix is returning fewer rows or a covering index that makes the scan narrower, not forcing the index.</p>\n<h3>The statistics are lying</h3>\n<p>Stale or missing statistics can make a selective predicate look non-selective. Compare estimated vs actual rows in the plan; if they diverge, refresh statistics and re-check before touching the index:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>UPDATE STATISTICS dbo.Orders WITH FULLSCAN;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>ANALYZE orders;</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>ANALYZE TABLE orders;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>ANALYZE orders;</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>EXEC DBMS_STATS.GATHER_TABLE_STATS(USER, 'ORDERS');</code></pre>\n<p>To see which choice the optimizer made and why, capture the plan and open it in the <a href=\"/tools/query-plan-viewer\">query plan viewer</a>; the <a href=\"/tools/sql-formatter\">formatter</a> helps when the query that carries the predicate arrived as one line.</p>","fix_html":"<p>Fix in the order the causes are listed: correct the index's leading column to match the predicate, de-function the predicate, align types, then (and only then) refresh statistics and re-measure. When the predicate genuinely matches most of the table, the winning move is usually a covering index so the scan reads a narrow index instead of wide table rows. SQL Server and PostgreSQL 11 or later keep the extra columns out of the key with INCLUDE:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX idx_orders_status_cover\nON orders (status) INCLUDE (customer_id, total);</code></pre>\n<p>On MySQL, SQLite and Oracle the columns join the key:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>CREATE INDEX idx_orders_status_cover\nON orders (status, customer_id, total);</code></pre>\n<p>Finally, confirm the fix stuck: <code>sys.dm_db_index_usage_stats</code> (SQL Server), <code>pg_stat_user_indexes.idx_scan</code> (PostgreSQL), <code>sys.schema_unused_indexes</code> (MySQL) and <code>DBA_INDEX_USAGE</code> (Oracle 12.2+) show whether the index is being used in production, not just in your test. The SQL Server and MySQL counters start over when the server restarts, PostgreSQL's survive a clean restart but reset after a crash or <code>pg_stat_reset()</code>, and <code>DBA_INDEX_USAGE</code> is kept in the dictionary across restarts.</p>","checklist_html":["Compare the index's leading column with the WHERE clause: do they match?","Search the predicate for functions and casts applied to the indexed column.","Check for implicit type mismatches between the column and the parameter or literal.","Rewrite leading-wildcard LIKEs as prefix matches, or plan a full-text or trigram index.","Compare estimated vs actual rows in the plan; refresh statistics if they diverge.","If selectivity is genuinely low, build a covering index instead of forcing the seek.","Re-capture the plan and confirm the SCAN became a SEEK with fewer logical reads."],"faqs":[{"question":"Should I force the index with a hint?","answer":"Only as a temporary measure with an expiry note. Hints fix the plan, not the reason the optimizer avoided the index, and the forced plan outlives the data change that made the index wrong. Fix the predicate, the types or the statistics and the optimizer will usually find the index on its own."},{"question":"The index is used in staging but not in production. Why?","answer":"Different data: production has more rows (the threshold where seek beats scan differs), different column distributions, or different statistics staleness. Compare estimated rows for the same predicate on both systems and refresh production statistics before concluding anything else."},{"question":"Do INCLUDE columns make an index more likely to be used?","answer":"They make a used index more useful - the seek can satisfy the SELECT from the index alone instead of fetching table rows (a key lookup). They do not change whether the index is chosen for filtering; that is decided by the key columns and the predicate."},{"question":"How do I know if an index is ever used at all?","answer":"Each engine tracks it: sys.dm_db_index_usage_stats on SQL Server (cleared on restart), pg_stat_user_indexes.idx_scan on PostgreSQL (plus last_idx_scan from PostgreSQL 16), sys.schema_unused_indexes on MySQL, and DBA_INDEX_USAGE on Oracle 12.2+, which is collected automatically but sampled by default, so a rarely used index can be missed; older Oracle releases need ALTER INDEX ... MONITORING USAGE and v$object_usage. Watch over a full business cycle - a monthly job's index looks unused until month-end. SQLite does not track index usage."},{"question":"Can an unused-looking plan still be optimal?","answer":"Yes. A full scan over a small table, a covering scan over a large one with low selectivity, or a hash join fed by scans can all be the cheapest plan. Judge by logical reads and time, not by whether the word 'Index' appears in the plan - the query plan viewer at /tools/query-plan-viewer makes the per-operator costs easy to read."}],"plan_group":null,"related_slugs":[]},"source_url":"https://sqlly.app/sql-performance/index-not-used","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/index-only-scan-heap-fetches","corpus":"sql-performance","engine":null,"language":"en","title":"Heap fetches in an index-only scan","description":"An index-only scan that reports Heap Fetches is still reading the table. Why the visibility map decides it, how to check it, and how VACUUM fixes it.","body":{"slug":"index-only-scan-heap-fetches","engines":["PostgreSQL"],"symptoms":["Slow query","Bad index usage"],"h1":"Heap fetches in an index-only scan","lede":"A PostgreSQL index-only scan that reports thousands of heap fetches is reading the table after all. Why the visibility map decides that, how to measure it, and how to keep the map current with VACUUM and autovacuum settings.","symptom_html":"<p>An <code>Index Only Scan</code> is supposed to answer the query from the index without touching the table. PostgreSQL can only do that for rows on pages it knows are visible to every transaction, and that knowledge lives in the table's visibility map, not in the index. For every row on a page that is not marked all-visible, the scan goes to the table to check the row. The plan counts those visits as <code>Heap Fetches</code>.</p>\n<p>With <code>Heap Fetches: 0</code> the scan is as cheap as it looks. With a heap fetch for most rows it is an ordinary index scan with a better name. The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> flags the second case. The examples use a shop schema with 400,000 orders, 40,000 of them for customer 1.</p>","diagnosis_html":"<h3>Read Heap Fetches next to the row count</h3>\n<p>Right after a <code>VACUUM</code>, a covering index gives a clean index-only scan:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_customer_total_idx ON orders (customer_id) INCLUDE (total);\n\nEXPLAIN (ANALYZE, BUFFERS)\nSELECT sum(total) FROM orders WHERE customer_id = 1;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>-&gt;  Index Only Scan using orders_customer_total_idx on orders  (cost=0.42..1331.42 rows=40400 width=6) (actual time=1.294..4.364 rows=40000.00 loops=1)\n      Heap Fetches: 0\n      Buffers: shared hit=1 read=156</code></pre>\n<p>Now change some of those rows. An update writes a new row version, and the pages it touches lose their all-visible mark:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>UPDATE orders SET status = status WHERE customer_id = 1 AND order_id % 2 = 0;\n\nEXPLAIN (ANALYZE, BUFFERS)\nSELECT sum(total) FROM orders WHERE customer_id = 1;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Buffers: shared hit=3691\n-&gt;  Index Only Scan using orders_customer_total_idx on orders  (cost=0.42..1403.42 rows=40400 width=6) (actual time=0.018..8.406 rows=40000.00 loops=1)\n      Heap Fetches: 60101\n      Buffers: shared hit=3691</code></pre>\n<p>Compare <code>Heap Fetches</code> with the <code>rows</code> the scan returned, and the <code>Buffers</code> line with the one before: 3,691 pages instead of 157. The node is still called <code>Index Only Scan</code>, but it now visits the table for every row on a page the update touched. The count is higher than the 40,000 rows returned because the index still points at the 20,000 old row versions, and each of those costs a visit too.</p>\n<h3>Check the visibility map</h3>\n<p><code>pg_class</code> stores how many of the table's pages were all-visible at the last <code>VACUUM</code> or <code>ANALYZE</code>. The planner uses that number to decide whether an index-only scan is worth choosing:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>ANALYZE orders;\n\nSELECT relpages, relallvisible,\n       round(100.0 * relallvisible / relpages, 1) AS pct_all_visible\nFROM pg_class\nWHERE oid = 'orders'::regclass;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>relpages | relallvisible | pct_all_visible\n    4482 |          1119 |            25.0</code></pre>\n<p>The <code>pg_visibility</code> extension reads the map itself, so the answer is current:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE EXTENSION IF NOT EXISTS pg_visibility;\n\nSELECT * FROM pg_visibility_map_summary('orders');</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>all_visible | all_frozen\n       1119 |          0</code></pre>\n<h3>See when the table was last vacuumed</h3>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SELECT relname, n_live_tup, n_dead_tup, last_vacuum, last_autovacuum\nFROM pg_stat_user_tables\nWHERE relname = 'orders';</code></pre>\n<p>Many dead tuples and an old or empty <code>last_autovacuum</code> mean autovacuum has not reached the table since the rows changed. The <a href=\"/sql-snippets/autovacuum-status\">autovacuum status snippet</a> runs the same check for every table.</p>","fix_html":"<h3>Vacuum the table</h3>\n<p><code>VACUUM</code> removes the dead row versions and marks the pages all-visible again. It does not block reads or writes.</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>VACUUM orders;\n\nEXPLAIN (ANALYZE, BUFFERS)\nSELECT sum(total) FROM orders WHERE customer_id = 1;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Buffers: shared hit=328\n-&gt;  Index Only Scan using orders_customer_total_idx on orders  (cost=0.42..1359.68 rows=38129 width=6) (actual time=0.006..1.807 rows=40000.00 loops=1)\n      Heap Fetches: 0\n      Buffers: shared hit=328</code></pre>\n<p>Plain <code>VACUUM</code> is enough. <code>VACUUM FULL</code> rewrites the table under an exclusive lock and is not needed for this.</p>\n<h3>Make autovacuum reach the table sooner</h3>\n<p>Autovacuum starts on a table when the dead rows exceed a fraction of the table, 20% by default. On a large table that is a long wait. Lower the fraction for the tables your index-only scans depend on:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>ALTER TABLE orders SET (autovacuum_vacuum_scale_factor = 0.02);</code></pre>\n<p>A table that only receives inserts has no dead rows to trigger on. For those, autovacuum uses a separate threshold based on inserted rows, which you can lower the same way:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>ALTER TABLE orders SET (autovacuum_vacuum_insert_scale_factor = 0.02);</code></pre>\n<p>The server-wide defaults are <a href=\"/sql-configuration/postgresql/autovacuum-vacuum-scale-factor\">autovacuum_vacuum_scale_factor</a> and the other <a href=\"/sql-configuration/postgresql/autovacuum\">autovacuum settings</a>.</p>\n<h3>Look for a transaction that holds vacuum back</h3>\n<p>If <code>VACUUM</code> runs and the heap fetches stay, an old transaction is probably still open. Vacuum cannot mark a page all-visible while any transaction might still need the old row versions on it. <code>VACUUM (VERBOSE)</code> says so in its report, as a count of tuples that are <code>dead but not yet removable</code>. Find the session that holds the oldest snapshot:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SELECT pid, state, age(backend_xmin) AS xmin_age, now() - xact_start AS open_for\nFROM pg_stat_activity\nWHERE backend_xmin IS NOT NULL AND pid &lt;&gt; pg_backend_pid()\nORDER BY age(backend_xmin) DESC;</code></pre>\n<p>End that transaction, then vacuum again.</p>\n<h3>When to leave it alone</h3>\n<p>A few heap fetches are normal on any table that is being written: the newest pages are never all-visible. Leave the plan alone when the fetches are a small share of the rows, or when the query is fast anyway. On a table where most rows change between vacuums, an index-only scan will never be clean, and the extra columns in the index are not buying anything; a plain index is smaller and does the same job.</p>","checklist_html":["Run EXPLAIN (ANALYZE, BUFFERS) and compare Heap Fetches with the rows the scan returned.","Check relallvisible against relpages in pg_class, or pg_visibility_map_summary.","Look at last_vacuum, last_autovacuum and n_dead_tup in pg_stat_user_tables.","Run VACUUM on the table and capture the plan again.","If nothing changed, find the oldest open transaction in pg_stat_activity.","Lower autovacuum_vacuum_scale_factor for the table so it is vacuumed more often."],"faqs":[{"question":"What does Heap Fetches mean in a PostgreSQL plan?","answer":"It is the number of rows for which an index-only scan had to read the table to check that the row is visible. The index holds the column values but not the visibility information, so the scan can skip the table only for pages the visibility map marks as all-visible."},{"question":"Why is my Index Only Scan slow?","answer":"Usually because of heap fetches. When most pages are not marked all-visible, the scan visits the table for most rows and costs about as much as an ordinary index scan. Vacuuming the table sets the visibility map and brings the fetch count down."},{"question":"Does ANALYZE fix heap fetches?","answer":"No. ANALYZE refreshes statistics, including the planner's count of all-visible pages, but it does not change the visibility map. Only VACUUM marks pages all-visible."},{"question":"Why did PostgreSQL stop choosing an index-only scan?","answer":"The planner estimates heap fetches from the share of all-visible pages recorded in pg_class. When that share is low it expects an index-only scan to visit the table anyway and may pick a bitmap or plain index scan. After a VACUUM the share rises and the index-only scan comes back."},{"question":"Do other databases have this problem?","answer":"Not in this form. It follows from PostgreSQL keeping row visibility in the table and not in the index. SQL Server, MySQL InnoDB and Oracle covering index reads do not report an equivalent of heap fetches."}],"plan_group":"Indexes and access paths","related_slugs":["key-lookup","full-table-scan","row-estimate-mismatch"]},"source_url":"https://sqlly.app/sql-performance/index-only-scan-heap-fetches","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/index-spool-automatic-index","corpus":"sql-performance","engine":null,"language":"en","title":"Index spools and automatic indexes","description":"An Index Spool in SQL Server or an AUTOMATIC INDEX in SQLite means the engine built a temporary index for one query. Create the real index instead.","body":{"slug":"index-spool-automatic-index","engines":["SQL Server","SQLite"],"symptoms":["Slow query","Bad index usage"],"h1":"Index spools and automatic indexes","lede":"When a query needs an index that does not exist, SQL Server and SQLite can build a temporary one while the query runs and throw it away afterwards. How to recognise an Index Spool or an AUTOMATIC INDEX in a plan and replace it with a permanent index.","symptom_html":"<p>Some plans contain an index that you never created. SQL Server calls the operator an <code>Index Spool</code> (logical operation <code>Eager Spool</code>): it reads a whole table, builds an index on it in tempdb, and then seeks into that copy. SQLite calls it an <code>AUTOMATIC INDEX</code>. In both cases the optimizer decided that repeating a full scan for every outer row would cost more than building an index first. The index is discarded when the statement ends and is built again on the next execution.</p>\n<p>It is the engine telling you exactly which index is missing. The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> flags both operators. The examples use a shop schema with 20,000 customers and 400,000 orders.</p>","diagnosis_html":"<h3>SQL Server: Index Spool</h3>\n<p>This query fetches the latest order of each German customer. There is no index on <code>Orders.CustomerId</code>:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS IO ON;\nGO\nSELECT c.CustomerId, x.OrderDate, x.Total\nFROM dbo.Customers AS c\nCROSS APPLY (\n    SELECT TOP (1) o.OrderDate, o.Total\n    FROM dbo.Orders AS o\n    WHERE o.CustomerId = c.CustomerId\n    ORDER BY o.OrderDate DESC\n) AS x\nWHERE c.Country = 'DE';</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Worktable'. Scan count 4000, logical reads 1165641, physical reads 0\nTable 'Orders'. Scan count 1, logical reads 2579, physical reads 0\nTable 'Customers'. Scan count 1, logical reads 115, physical reads 0</code></pre>\n<p><code>Orders</code> is scanned once, and nearly all the reads are on <code>Worktable</code>: that is the spool being built and then searched once per customer. The text plan names the operator and the columns it indexes:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET SHOWPLAN_TEXT ON;\nGO\nSELECT c.CustomerId, x.OrderDate, x.Total\nFROM dbo.Customers AS c\nCROSS APPLY (\n    SELECT TOP (1) o.OrderDate, o.Total\n    FROM dbo.Orders AS o\n    WHERE o.CustomerId = c.CustomerId\n    ORDER BY o.OrderDate DESC\n) AS x\nWHERE c.Country = 'DE';\nGO\nSET SHOWPLAN_TEXT OFF;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>|--Index Spool(SEEK:([o].[CustomerId]=[learnfx].[dbo].[Customers].[CustomerId] as [c].[CustomerId]))</code></pre>\n<p>The <code>SEEK</code> predicate of the spool is the key of the index you need. The columns the spool outputs are the ones to include.</p>\n<h3>SQLite: AUTOMATIC INDEX</h3>\n<p>SQLite builds an automatic index when a join has no index on either side. This query matches orders to customers by timestamp, and neither column is indexed:</p>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>EXPLAIN QUERY PLAN\nSELECT c.customer_id, o.order_id\nFROM customers AS c\nJOIN orders AS o ON o.order_date = c.created_at;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\" data-role=\"output\"><code>|--SCAN c\n`--SEARCH o USING AUTOMATIC COVERING INDEX (order_date=?)</code></pre>\n<p>The line names the table and the column: SQLite will read all of <code>orders</code>, build an index on <code>order_date</code>, and use it for each customer. Nothing is stored in the database file; the schema has no new index afterwards.</p>\n<p>To see what the query would do without it, turn the feature off for the connection:</p>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>PRAGMA automatic_index = OFF;\n\nEXPLAIN QUERY PLAN\nSELECT c.customer_id, o.order_id\nFROM customers AS c\nJOIN orders AS o ON o.order_date = c.created_at;\n\nPRAGMA automatic_index = ON;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\" data-role=\"output\"><code>|--SCAN c\n`--SCAN o</code></pre>\n<p>Two nested scans: 20,000 passes over 400,000 rows. The automatic index is the better of two bad options, which is why <a href=\"/sql-configuration/sqlite/automatic-index\">automatic_index</a> is on by default.</p>","fix_html":"<h3>Create the index the engine keeps building</h3>\n<p>In SQL Server, use the spool's seek columns as the key, add the <code>ORDER BY</code> column so the latest order is found without a sort, and include the other columns the query reads:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX IX_Orders_CustomerId_OrderDate\n    ON dbo.Orders (CustomerId, OrderDate DESC) INCLUDE (Total);\nGO\nSELECT c.CustomerId, x.OrderDate, x.Total\nFROM dbo.Customers AS c\nCROSS APPLY (\n    SELECT TOP (1) o.OrderDate, o.Total\n    FROM dbo.Orders AS o\n    WHERE o.CustomerId = c.CustomerId\n    ORDER BY o.OrderDate DESC\n) AS x\nWHERE c.Country = 'DE';</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 4000, logical reads 12777, physical reads 0\nTable 'Customers'. Scan count 1, logical reads 115, physical reads 0</code></pre>\n<p>The worktable is gone and each customer costs one seek.</p>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>CREATE INDEX orders_date_idx ON orders (order_date);\n\nEXPLAIN QUERY PLAN\nSELECT c.customer_id, o.order_id\nFROM customers AS c\nJOIN orders AS o ON o.order_date = c.created_at;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\" data-role=\"output\"><code>|--SCAN c\n`--SEARCH o USING COVERING INDEX orders_date_idx (order_date=?)</code></pre>\n<h3>Run ANALYZE in SQLite</h3>\n<p>SQLite chooses join order and automatic indexes from table sizes. Without statistics it has to guess them. Run <code>ANALYZE</code> once the tables hold realistic data, so that the plan you inspect is the plan production will get:</p>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>ANALYZE;</code></pre>\n<h3>When to leave it alone</h3>\n<p>A permanent index costs space and slows every write to the table. For a report that runs once a night, letting the engine build a throwaway index can be the cheaper arrangement. Create the index when the query runs often, or when the build dominates its run time. In SQL Server, compare the reads on <code>Worktable</code> with the rest of the query to judge that.</p>","checklist_html":["Look for Index Spool (Eager Spool) in SQL Server plans or AUTOMATIC INDEX in SQLite plans.","Read the seek columns of the spool or the column named in the AUTOMATIC INDEX line.","In SQL Server, check the Worktable reads in SET STATISTICS IO output.","Create a permanent index on those columns, with the other columns the query reads included.","Capture the plan again and confirm the spool or automatic index is gone.","Weigh the index against how often the query runs and how heavily the table is written."],"faqs":[{"question":"What is an Eager Index Spool in SQL Server?","answer":"It is an operator that reads all rows from its input, builds a temporary index on them in tempdb, and then serves seeks from that index. The optimizer adds it under a nested loop when the table has no suitable index. The temporary index is rebuilt every time the query runs."},{"question":"What does AUTOMATIC INDEX mean in SQLite?","answer":"SQLite will build a temporary index for the duration of the statement because the join or lookup has no permanent index to use. EXPLAIN QUERY PLAN shows it as SEARCH ... USING AUTOMATIC INDEX or AUTOMATIC COVERING INDEX, with the indexed column in parentheses."},{"question":"Is an index spool bad?","answer":"It is better than the plan the optimizer would otherwise have chosen, but it is repeated work: the same index is built from scratch on every execution. If the query runs regularly, a permanent index removes that cost."},{"question":"Should I turn off automatic_index in SQLite?","answer":"Usually not. Turning it off does not make the query faster; it replaces the temporary index with repeated full scans. It is useful as a diagnostic, to make missing indexes show up as slow queries during testing."},{"question":"Where does the Worktable in STATISTICS IO come from?","answer":"Worktable is a temporary structure in tempdb used by spools, some sorts and hash operations. Large logical reads on Worktable next to a plan with an Index Spool are the cost of building and searching the spool."}],"plan_group":"Indexes and access paths","related_slugs":["missing-index","join-algorithms","correlated-subquery"]},"source_url":"https://sqlly.app/sql-performance/index-spool-automatic-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/join-algorithms","corpus":"sql-performance","engine":null,"language":"en","title":"Nested loop, hash and merge joins","description":"Each join method is right for some row counts and wrong for others. How to read nested loop, hash and merge joins in a plan and fix the slow ones.","body":{"slug":"join-algorithms","engines":["PostgreSQL","MySQL","SQL Server","Oracle"],"symptoms":["Slow query","High CPU"],"h1":"Nested loop, hash and merge joins","lede":"A plan joins tables with nested loops, a hash table or a merge of sorted inputs. Each is the best choice for some row counts and a poor one for others. How to read them and what to fix when the wrong one was chosen or the right one has no index to use.","symptom_html":"<p>There are three ways to join two inputs, and every engine picks among them from its row estimates:</p>\n<ul>\n<li><strong>Nested loop.</strong> For each row of the outer input, look up the matching rows in the inner input. Very fast for a few outer rows with an index on the inner side. The inner side runs once per outer row, so the cost grows with the outer row count.</li>\n<li><strong>Hash join.</strong> Read one input completely into an in-memory hash table (the build side), then read the other (the probe side) and look each row up. Good for large inputs with no useful index. Needs memory for the build side.</li>\n<li><strong>Merge join.</strong> Walk two inputs that are sorted on the join key side by side. Cheap when both arrive sorted from indexes; otherwise it pays for sorts first.</li>\n</ul>\n<p>None of them is bad. A join is slow when the method does not suit the real row counts, or when a nested loop has no index for its inner side. The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> flags nested loops that run their inner side many times, hash joins built on the larger input and MySQL joins that fall back to the join buffer. The examples use a shop schema with 20,000 customers, 400,000 orders and 800,000 order items.</p>","diagnosis_html":"<h3>A join with no index on the join column</h3>\n<p>The most common slow join is a lookup of child rows where the foreign key column has no index. A foreign key constraint does not create one on PostgreSQL, SQL Server or Oracle. To find one customer's orders, the engine reads every order:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT c.email, o.order_id, o.total\nFROM customers AS c\nJOIN orders AS o ON o.customer_id = c.customer_id\nWHERE c.email = 'user4242@example.com';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Gather  (cost=1417.01..8005.27 rows=20 width=31) (actual rows=20.00 loops=1)\n  Workers Planned: 2\n  Workers Launched: 2\n  -&gt;  Hash Join  (cost=417.01..7003.27 rows=8 width=31) (actual rows=6.67 loops=3)\n        Hash Cond: (o.customer_id = c.customer_id)\n        -&gt;  Parallel Seq Scan on orders o  (cost=0.00..6148.67 rows=166667 width=14) (actual rows=133333.33 loops=3)\n        -&gt;  Hash  (cost=417.00..417.00 rows=1 width=25) (actual rows=1.00 loops=3)\n              Buckets: 1024  Batches: 1  Memory Usage: 9kB\n              -&gt;  Seq Scan on customers c  (cost=0.00..417.00 rows=1 width=25) (actual rows=1.00 loops=3)\n                    Filter: ((email)::text = 'user4242@example.com'::text)\n                    Rows Removed by Filter: 19999</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS IO ON;\nGO\nSELECT c.Email, o.OrderId, o.Total\nFROM dbo.Customers AS c\nJOIN dbo.Orders AS o ON o.CustomerId = c.CustomerId\nWHERE c.Email = 'user4242@example.com';</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 2579, physical reads 0\nTable 'Customers'. Scan count 1, logical reads 115, physical reads 0</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>EXPLAIN PLAN FOR\nSELECT c.email, o.order_id, o.total\nFROM customers c\nJOIN orders o ON o.customer_id = c.customer_id\nWHERE c.email = 'user4242@example.com';\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation          | Name      | Rows  | Bytes | Cost (%CPU)| Time     |\n|   0 | SELECT STATEMENT   |           |    22 |   924 |   685   (1)| 00:00:01 |\n|*  1 |  HASH JOIN         |           |    22 |   924 |   685   (1)| 00:00:01 |\n|*  2 |   TABLE ACCESS FULL| CUSTOMERS |     1 |    27 |    34   (0)| 00:00:01 |\n|   3 |   TABLE ACCESS FULL| ORDERS    |   400K|  5859K|   650   (1)| 00:00:01 |</code></pre>\n<p>A hash join over a full scan of the larger table, to return about 20 rows, is the pattern to look for.</p>\n<h3>MySQL: a reversed join, or Using join buffer</h3>\n<p>MySQL prefers nested loops with an index on the inner table. With no index on <code>orders.customer_id</code> it cannot look up a customer's orders, so it turns the join round: it reads every order and looks up each order's customer by primary key.</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN SELECT c.email, o.order_id, o.total\nFROM customers AS c\nJOIN orders AS o ON o.customer_id = c.customer_id\nWHERE c.email = 'user4242@example.com'\\G</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>table: o\n type: ALL\n  key: NULL\n rows: 398228\nExtra: NULL\ntable: c\n type: eq_ref\n  key: PRIMARY\n rows: 1\nExtra: Using where</code></pre>\n<p>When neither table has an index on the join column, MySQL reads both in full and joins them through the join buffer, which the plan reports in <code>Extra</code>:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN SELECT c.customer_id, o.order_id\nFROM customers AS c\nJOIN orders AS o ON o.order_date = c.created_at\\G</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>table: c\n type: ALL\n  key: NULL\n rows: 19965\nExtra: NULL\ntable: o\n type: ALL\n  key: NULL\n rows: 398228\nExtra: Using where; Using join buffer (hash join)</code></pre>\n<p>MariaDB prints the same condition as <code>Using join buffer (flat, BNL join)</code>. Either way it says that the join found no index to use.</p>\n<h3>A nested loop that runs more often than planned</h3>\n<p>In a plan with actual counts, the inner side of a nested loop shows how many times it ran: <code>loops</code> in PostgreSQL and MySQL, <code>Number of Executions</code> in SQL Server, <code>Starts</code> in Oracle. Compare it with the rows the optimizer expected from the outer side:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT o.order_id, i.product_id, i.quantity\nFROM orders AS o\nJOIN order_items AS i ON i.order_id = o.order_id\nWHERE o.customer_id = 1 AND o.status = 'pending';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Gather  (cost=1000.42..10115.80 rows=868 width=12) (actual rows=8000.00 loops=1)\n  Workers Planned: 2\n  Workers Launched: 2\n  -&gt;  Nested Loop  (cost=0.42..9029.00 rows=362 width=12) (actual rows=2666.67 loops=3)\n        -&gt;  Parallel Seq Scan on orders o  (cost=0.00..6982.00 rows=181 width=4) (actual rows=1333.33 loops=3)\n              Filter: ((customer_id = 1) AND ((status)::text = 'pending'::text))\n              Rows Removed by Filter: 132000\n        -&gt;  Index Scan using order_items_pkey on order_items i  (cost=0.42..11.29 rows=2 width=12) (actual rows=2.00 loops=4000)\n              Index Cond: (order_id = o.order_id)\n              Index Searches: 4000</code></pre>\n<p>The optimizer chose the loop for the few hundred orders it expected. Ten times as many arrived, and the index on <code>order_items</code> was searched once for each. Each search is cheap; the plan is slow only if the count is far beyond what was planned. The cause is the <a href=\"/sql-performance/row-estimate-mismatch\">row estimate</a>, not the loop.</p>\n<h3>The build side of a hash join</h3>\n<p>A hash join should build its hash table from the smaller input. In PostgreSQL the build side is the input under the <code>Hash</code> node; in SQL Server it is the upper input of the <code>Hash Match</code>; in Oracle the first child of <code>HASH JOIN</code>.</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SET max_parallel_workers_per_gather = 0;\n\nEXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT c.country, count(*)\nFROM orders AS o\nJOIN customers AS c ON c.customer_id = o.customer_id\nGROUP BY c.country;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>HashAggregate  (cost=12149.22..12149.27 rows=5 width=11) (actual rows=5.00 loops=1)\n  -&gt;  Hash Join  (cost=617.00..10149.22 rows=400000 width=3) (actual rows=400000.00 loops=1)\n        Hash Cond: (o.customer_id = c.customer_id)\n        -&gt;  Seq Scan on orders o  (cost=0.00..8482.00 rows=400000 width=4) (actual rows=400000.00 loops=1)\n        -&gt;  Hash  (cost=367.00..367.00 rows=20000 width=7) (actual rows=20000.00 loops=1)\n              Buckets: 32768  Batches: 1  Memory Usage: 1038kB\n              -&gt;  Seq Scan on customers c  (cost=0.00..367.00 rows=20000 width=7) (actual rows=20000.00 loops=1)</code></pre>\n<p>Here 20,000 customers are hashed and 400,000 orders probe the table, which is the right way round. When the estimates are wrong the engine can hash the large side by mistake. The signs are a <code>Hash</code> node with far more actual rows than estimated, and <code>Batches</code> above 1, meaning the table <a href=\"/sql-performance/sort-and-hash-spills\">spilled to disk</a>.</p>","fix_html":"<h3>Index the join column on the many side</h3>\n<p>Create an index on the foreign key column. The join becomes a nested loop that reads only the matching rows:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nEXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT c.email, o.order_id, o.total\nFROM customers AS c\nJOIN orders AS o ON o.customer_id = c.customer_id\nWHERE c.email = 'user4242@example.com';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Nested Loop  (cost=4.60..509.18 rows=20 width=31) (actual rows=20.00 loops=1)\n  -&gt;  Seq Scan on customers c  (cost=0.00..417.00 rows=1 width=25) (actual rows=1.00 loops=1)\n        Filter: ((email)::text = 'user4242@example.com'::text)\n        Rows Removed by Filter: 19999\n  -&gt;  Bitmap Heap Scan on orders o  (cost=4.60..91.95 rows=23 width=14) (actual rows=20.00 loops=1)\n        Recheck Cond: (c.customer_id = customer_id)\n        Heap Blocks: exact=20\n        -&gt;  Bitmap Index Scan on orders_customer_idx  (cost=0.00..4.60 rows=23 width=0) (actual rows=20.00 loops=1)\n              Index Cond: (customer_id = c.customer_id)\n              Index Searches: 1</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nEXPLAIN SELECT c.email, o.order_id, o.total\nFROM customers AS c\nJOIN orders AS o ON o.customer_id = c.customer_id\nWHERE c.email = 'user4242@example.com'\\G</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>table: c\n type: ALL\n  key: NULL\n rows: 20151\nExtra: Using where\ntable: o\n type: ref\n  key: orders_customer_idx\n rows: 22\nExtra: NULL</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId) INCLUDE (Total);\nGO\nSELECT c.Email, o.OrderId, o.Total\nFROM dbo.Customers AS c\nJOIN dbo.Orders AS o ON o.CustomerId = c.CustomerId\nWHERE c.Email = 'user4242@example.com';</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 3, physical reads 0\nTable 'Customers'. Scan count 1, logical reads 115, physical reads 0</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nEXPLAIN PLAN FOR\nSELECT c.email, o.order_id, o.total\nFROM customers c\nJOIN orders o ON o.customer_id = c.customer_id\nWHERE c.email = 'user4242@example.com';\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation                    | Name                | Rows  | Bytes | Cost (%CPU)| Time     |\n|   0 | SELECT STATEMENT             |                     |    22 |   924 |    56   (0)| 00:00:01 |\n|   1 |  NESTED LOOPS                |                     |    22 |   924 |    56   (0)| 00:00:01 |\n|   2 |   NESTED LOOPS               |                     |    22 |   924 |    56   (0)| 00:00:01 |\n|*  3 |    TABLE ACCESS FULL         | CUSTOMERS           |     1 |    27 |    34   (0)| 00:00:01 |\n|*  4 |    INDEX RANGE SCAN          | ORDERS_CUSTOMER_IDX |    22 |       |     2   (0)| 00:00:01 |\n|   5 |   TABLE ACCESS BY INDEX ROWID| ORDERS              |    22 |   330 |    22   (0)| 00:00:01 |</code></pre>\n<p>The customer is still found by scanning <code>customers</code>, because <code>email</code> has no index either; that is a separate <a href=\"/sql-performance/full-table-scan\">full table scan</a> to fix. The <a href=\"/sql-snippets/missing-fk-index-candidates\">missing foreign key index snippet</a> lists every foreign key without a supporting index.</p>\n<h3>Fix the estimate behind a wrong method</h3>\n<p>When a nested loop runs many times more than planned, or a hash join built the wrong side, find the operator below it where estimated and actual rows diverge and correct that: refresh statistics, add extended statistics for related columns, or deal with a sniffed parameter. The join method then corrects itself. See <a href=\"/sql-performance/row-estimate-mismatch\">row estimate mismatch</a>.</p>\n<h3>Make both join columns the same type</h3>\n<p>A join between columns of different types can leave the index on one side unusable, which looks exactly like a missing index. Check the declared types before adding anything; the details are under <a href=\"/sql-performance/implicit-conversion\">implicit conversions</a>.</p>\n<h3>When to leave it alone</h3>\n<p>A hash join between two large tables that the query has to read in full is the correct plan, and so is a nested loop that runs a few hundred indexed lookups. Do not force a join method with hints because one looks wrong by name. Judge by the numbers: rows in, times executed, and whether the inner side used an index.</p>","checklist_html":["Identify the join method and which input is the outer or build side.","For a nested loop, read how many times the inner side ran and whether it used an index.","For a hash join, check that the build side is the smaller input and that it stayed in memory.","Compare estimated and actual rows on both inputs.","Index the join column of the table being looked up, usually the foreign key.","Check that both join columns have the same data type.","Capture the plan again and compare rows read."],"faqs":[{"question":"Which join type is fastest?","answer":"It depends on the row counts. A nested loop is fastest when a few rows drive indexed lookups. A hash join is fastest when both inputs are large and unsorted. A merge join is fastest when both inputs already arrive sorted on the join key. The optimizer chooses from its estimates, so a wrong estimate gives a wrong choice."},{"question":"Why is my nested loop slow?","answer":"Either the inner side has no index on the join column, so each loop scans, or the loop runs far more times than the optimizer planned because the outer row estimate was too low. The plan shows both: the access method on the inner side and its execution count."},{"question":"Do foreign keys create indexes automatically?","answer":"MySQL InnoDB creates an index on the referencing column if none exists. PostgreSQL, SQL Server and Oracle do not: the primary key side is indexed, the foreign key column is not unless you add an index yourself."},{"question":"What does Using join buffer mean in MySQL?","answer":"MySQL found no index on the join column of that table, so it reads the table once and matches rows through an in-memory buffer, with a hash join in MySQL 8 or a block nested loop in MariaDB and older versions. An index on the join column usually replaces it with an indexed lookup."},{"question":"Should I use join hints to force a hash join or a loop?","answer":"Rarely. A hint fixes the method for every future data size and parameter value, including the ones where it is wrong. Correcting the row estimate or adding the missing index lets the optimizer make the choice and keep making it as the data changes."}],"plan_group":"Joins and subqueries","related_slugs":["row-estimate-mismatch","join-row-explosion","sort-and-hash-spills"]},"source_url":"https://sqlly.app/sql-performance/join-algorithms","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/join-row-explosion","corpus":"sql-performance","engine":null,"language":"en","title":"Joins that multiply rows","description":"A join that returns more rows than either input is a missing join condition or a one-to-many fan-out. How to spot both in a plan and rewrite the query.","body":{"slug":"join-row-explosion","engines":["PostgreSQL","MySQL","SQL Server","Oracle"],"symptoms":["Slow query","High CPU"],"h1":"Joins that multiply rows","lede":"A join that produces far more rows than it was given is either missing its join condition or fanning out across a one-to-many relationship. How both look in a plan, why DISTINCT only hides them, and the rewrites that remove the extra rows.","symptom_html":"<p>Follow the row counts up a plan and they normally shrink or stay level. When a join outputs many more rows than its larger input, the query is multiplying rows. There are two causes. A join with no condition pairs every row of one input with every row of the other, a cartesian product. A join from a parent to a child table, or to two unrelated child tables at once, repeats each parent row once per child. Often a <code>DISTINCT</code> or <code>GROUP BY</code> sits on top to collapse the duplicates again, so the result looks right while the work underneath is many times larger than needed.</p>\n<p>The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> flags joins with no join predicate and joins whose output is collapsed again above them. The examples use a shop schema with 20,000 customers, 400,000 orders and 800,000 order items.</p>","diagnosis_html":"<h3>A join with no join condition</h3>\n<p>This query lists two tables and filters each, but never says how they relate. 4,000 customers times 4,000 pending orders is 16 million rows:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (COSTS OFF)\nSELECT c.email, o.order_id\nFROM customers AS c, orders AS o\nWHERE c.country = 'DE' AND o.status = 'pending';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Nested Loop\n  -&gt;  Seq Scan on orders o\n        Filter: ((status)::text = 'pending'::text)\n  -&gt;  Materialize\n        -&gt;  Seq Scan on customers c\n              Filter: (country = 'DE'::bpchar)</code></pre>\n<p>In PostgreSQL the sign is a <code>Nested Loop</code> with no <code>Join Filter</code> and no <code>Index Cond</code> that refers to the other table. The other engines name the problem:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN FORMAT=TREE\nSELECT c.email, o.order_id\nFROM customers AS c, orders AS o\nWHERE c.country = 'DE' AND o.status = 'pending';</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Inner hash join (no condition)  (cost=8.21e+6 rows=8.03e+6)\n    -&gt; Filter: (o.`status` = 'pending')  (cost=87.7 rows=39864)\n        -&gt; Table scan on o  (cost=87.7 rows=398641)\n    -&gt; Hash\n        -&gt; Filter: (c.country = 'DE')  (cost=2040 rows=2015)\n            -&gt; Table scan on c  (cost=2040 rows=20154)</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>EXPLAIN PLAN FOR\nSELECT c.email, o.order_id\nFROM customers c, orders o\nWHERE c.country = 'DE' AND o.status = 'pending';\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation            | Name      | Rows  | Bytes | Cost (%CPU)| Time     |\n|   0 | SELECT STATEMENT     |           |    16M|   595M|   129K  (1)| 00:00:06 |\n|   1 |  MERGE JOIN CARTESIAN|           |    16M|   595M|   129K  (1)| 00:00:06 |\n|*  2 |   TABLE ACCESS FULL  | ORDERS    |  4000 | 56000 |   650   (1)| 00:00:01 |\n|   3 |   BUFFER SORT        |           |  4000 |    97K|   128K  (1)| 00:00:06 |\n|*  4 |    TABLE ACCESS FULL | CUSTOMERS |  4000 |    97K|    32   (0)| 00:00:01 |</code></pre>\n<p>SQL Server puts a warning on the join operator, shown as <code>No Join Predicate</code> in the graphical plan and as this element in the plan XML:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET SHOWPLAN_XML ON;\nGO\nSELECT c.Email, o.OrderId\nFROM dbo.Customers AS c, dbo.Orders AS o\nWHERE c.Country = 'DE' AND o.Status = 'pending';\nGO\nSET SHOWPLAN_XML OFF;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>&lt;Warnings NoJoinPredicate=\"1\" /&gt;</code></pre>\n<h3>A fan-out that DISTINCT collapses again</h3>\n<p>Joining orders to their items returns one row per item. If the query only wants the orders, a <code>DISTINCT</code> has to remove the repeats:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT DISTINCT o.order_id, o.total\nFROM orders AS o\nJOIN order_items AS i ON i.order_id = o.order_id\nWHERE o.customer_id = 1;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>HashAggregate  (cost=25348.89..25742.89 rows=39400 width=10) (actual rows=40000.00 loops=1)\n  Group Key: o.order_id, o.total\n  Batches: 1  Memory Usage: 2329kB\n  -&gt;  Gather  (cost=7770.55..24954.89 rows=78800 width=10) (actual rows=80000.00 loops=1)\n        Workers Planned: 2\n        Workers Launched: 2\n        -&gt;  Parallel Hash Join  (cost=6770.55..16074.89 rows=32833 width=10) (actual rows=26666.67 loops=3)\n              Hash Cond: (i.order_id = o.order_id)\n              -&gt;  Parallel Seq Scan on order_items i  (cost=0.00..8429.33 rows=333333 width=4) (actual rows=266666.67 loops=3)\n              -&gt;  Parallel Hash  (cost=6565.33..6565.33 rows=16417 width=10) (actual rows=13333.33 loops=3)\n                    Buckets: 65536  Batches: 1  Memory Usage: 2464kB\n                    -&gt;  Parallel Seq Scan on orders o  (cost=0.00..6565.33 rows=16417 width=10) (actual rows=13333.33 loops=3)\n                          Filter: (customer_id = 1)\n                          Rows Removed by Filter: 120000</code></pre>\n<p>Read the actual rows from the bottom up: 40,000 orders go into the join, 80,000 rows come out, and the <code>HashAggregate</code> at the top brings them back to 40,000. A join whose output is larger than its inputs, directly under an operator that removes duplicates, is the pattern.</p>\n<h3>Totals that come out too high</h3>\n<p>Without the <code>DISTINCT</code>, a fan-out makes aggregates wrong, not just slow. Each order's total is counted once per item:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SELECT count(*) AS order_rows, sum(o.total) AS revenue\nFROM orders AS o\nJOIN order_items AS i ON i.order_id = o.order_id\nWHERE o.customer_id = 4242;\n\nSELECT count(*) AS order_rows, sum(total) AS revenue\nFROM orders\nWHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>order_rows | revenue\n        39 | 13824.70\norder_rows | revenue\n        20 | 7093.00</code></pre>\n<p>The customer has 20 orders. The joined query counts 39 rows and nearly doubles the revenue.</p>","fix_html":"<h3>Add the missing join condition</h3>\n<p>Write joins with <code>JOIN ... ON</code> so that a join without a condition is a syntax error instead of a slow query:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (COSTS OFF)\nSELECT c.email, o.order_id\nFROM customers AS c\nJOIN orders AS o ON o.customer_id = c.customer_id\nWHERE c.country = 'DE' AND o.status = 'pending';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Gather\n  Workers Planned: 2\n  -&gt;  Hash Join\n        Hash Cond: (o.customer_id = c.customer_id)\n        -&gt;  Parallel Seq Scan on orders o\n              Filter: ((status)::text = 'pending'::text)\n        -&gt;  Hash\n              -&gt;  Seq Scan on customers c\n                    Filter: (country = 'DE'::bpchar)</code></pre>\n<p>In a query with many tables, check that every table is connected to the rest by at least one condition, and that composite keys are joined on all of their columns. Joining on half of a two-column key produces a smaller version of the same multiplication.</p>\n<h3>Use EXISTS when you only test for a match</h3>\n<p>If the query needs no columns from the child table, ask whether a matching row exists. The engine stops at the first match for each order and returns each order once, so there is nothing to de-duplicate:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT o.order_id, o.total\nFROM orders AS o\nWHERE o.customer_id = 1\n  AND EXISTS (SELECT 1 FROM order_items AS i WHERE i.order_id = o.order_id);</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Gather  (cost=1000.42..21702.05 rows=34101 width=10) (actual rows=40000.00 loops=1)\n  Workers Planned: 2\n  Workers Launched: 2\n  -&gt;  Nested Loop Semi Join  (cost=0.42..17291.95 rows=14209 width=10) (actual rows=13333.33 loops=3)\n        -&gt;  Parallel Seq Scan on orders o  (cost=0.00..6565.33 rows=16417 width=10) (actual rows=13333.33 loops=3)\n              Filter: (customer_id = 1)\n              Rows Removed by Filter: 120000\n        -&gt;  Index Only Scan using order_items_pkey on order_items i  (cost=0.42..0.79 rows=2 width=4) (actual rows=1.00 loops=40000)\n              Index Cond: (order_id = o.order_id)\n              Heap Fetches: 0\n              Index Searches: 40000</code></pre>\n<p>The plan now uses a semi join and its output is 40,000 rows, with no aggregate above it. The same rewrite works in every engine.</p>\n<h3>Aggregate the child rows before joining</h3>\n<p>When you do need numbers from the child table, reduce it to one row per parent first and then join. Each order appears once, so its total is counted once:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SELECT count(*) AS order_rows, sum(o.total) AS revenue, sum(i.item_count) AS items\nFROM orders AS o\nJOIN (\n    SELECT order_id, count(*) AS item_count\n    FROM order_items\n    GROUP BY order_id\n) AS i ON i.order_id = o.order_id\nWHERE o.customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>order_rows | revenue | items\n        20 | 7093.00 |    39</code></pre>\n<p>The same applies when a parent is joined to two different child tables: aggregate each child separately, then join the results to the parent.</p>\n<h3>When to leave it alone</h3>\n<p>A cartesian product is correct when you mean it: pairing every date with every product to build a report grid, or joining to a table that holds a single row. Engines also choose a cartesian join on purpose when one input is known to be one row. And a join that returns more rows than its input is simply the answer when the query asks for the child rows. Act when the extra rows are thrown away again further up, or when the result is wrong.</p>","checklist_html":["Follow actual row counts up the plan and find the join where they jump.","Check that the join has a condition linking the two inputs.","Check composite keys are joined on every column.","Look above the join for DISTINCT or GROUP BY that collapses the rows again.","Replace joins used only as an existence test with EXISTS.","Aggregate child tables to one row per parent before joining them.","Compare totals against a query on the parent table alone."],"faqs":[{"question":"What is a cartesian product in a query plan?","answer":"It is a join with no condition, so every row from one input is paired with every row from the other. Oracle labels it MERGE JOIN CARTESIAN, MySQL shows a join with no condition, SQL Server adds a No Join Predicate warning, and PostgreSQL shows a nested loop without a join filter."},{"question":"Why does my join return duplicate rows?","answer":"Because the join follows a one-to-many relationship: each row on the one side is returned once for every matching row on the many side. If you only need the one side, use EXISTS. If you need figures from the many side, aggregate it to one row per key before joining."},{"question":"Is SELECT DISTINCT a fix for duplicate rows from a join?","answer":"It hides them at a cost. The join still produces every duplicate, and the engine then has to sort or hash the whole result to remove them. It also does nothing for sums and counts computed before the DISTINCT. Removing the fan-out is cheaper and safer."},{"question":"Why is my SUM too high after adding a join?","answer":"The new join repeats each row once per match, and the sum adds the repeated values. Compare the result with the same sum on the base table alone. Aggregate the joined table in a subquery first so that the join cannot multiply rows."},{"question":"Does the old comma join syntax cause cartesian products?","answer":"Not by itself, but it makes them easy to write. With tables listed after FROM and conditions in WHERE, leaving out one condition still gives a valid query. With JOIN ... ON, every join has to state its condition."}],"plan_group":"Joins and subqueries","related_slugs":["join-algorithms","correlated-subquery","row-estimate-mismatch"]},"source_url":"https://sqlly.app/sql-performance/join-row-explosion","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/key-lookup","corpus":"sql-performance","engine":null,"language":"en","title":"Key lookups and covering indexes","description":"The index finds the rows, then the plan visits the table once per row for the other columns. How to spot the lookup on five engines and cover the query.","body":{"slug":"key-lookup","engines":["SQL Server","PostgreSQL","MySQL","SQLite","Oracle"],"symptoms":["Slow query","Bad index usage"],"h1":"Key lookups and covering indexes","lede":"An index found the rows, but the query needs columns the index does not have, so the plan fetches every row from the table one at a time. How to see that step on each engine, cover the query with the right index, and when the lookup is fine.","symptom_html":"<p>An index holds its key columns and a pointer to the row. When the query asks for any other column, the engine follows the pointer for every row the index returns. SQL Server draws that step as a <code>Key Lookup</code> (or a <code>RID Lookup</code> on a heap), Oracle as <code>TABLE ACCESS BY INDEX ROWID</code>. PostgreSQL, MySQL and SQLite do the same work without a separate operator: you recognise it by the difference between an index scan and an index-only or covering scan.</p>\n<p>Twenty lookups are nothing. Forty thousand are forty thousand random reads, and well before that point the optimizer gives up on the index and scans the table instead. The examples use a shop schema with 400,000 orders, where customer 4242 has 20 orders and customer 1 has 40,000. Paste your own plan into the <a href=\"/tools/query-plan-viewer\">query plan viewer</a> to see how many times its lookup ran.</p>","diagnosis_html":"<h3>SQL Server: Key Lookup under a Nested Loops join</h3>\n<p>With an index on <code>CustomerId</code> only, a query that also returns <code>OrderDate</code> and <code>Total</code> has to go back to the clustered index for them:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);\nGO\nSET STATISTICS IO ON;\nSET STATISTICS XML ON;\nGO\nSELECT OrderId, OrderDate, Total FROM dbo.Orders WHERE CustomerId = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 64, physical reads 0</code></pre>\n<p>The plan is a <code>Nested Loops</code> join with an <code>Index Seek</code> on top and a <code>Key Lookup (Clustered)</code> below it that runs once per row. In the plan XML the lookup is a <code>Clustered Index Seek</code> with <code>Lookup=\"1\"</code>, and its <code>Output List</code> names the columns the index was missing. Now ask for the customer with 40,000 orders:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT OrderId, OrderDate, Total FROM dbo.Orders WHERE CustomerId = 1;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 2579, physical reads 0</code></pre>\n<p>The index is no longer used at all. 40,000 lookups would cost more than reading the whole table, so the plan is a <code>Clustered Index Scan</code>. A lookup that is cheap for a small customer turns into a full scan for a large one, which is also one of the classic causes of <a href=\"/sql-performance/parameter-sniffing\">parameter sniffing</a> trouble.</p>\n<h3>SQL Server: RID Lookup on a heap</h3>\n<p>A table without a clustered index is a heap, and its indexes point at physical row locations. The lookup is then a <code>RID Lookup</code>:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT * INTO dbo.OrdersHeap FROM dbo.Orders;\nCREATE INDEX IX_OrdersHeap_CustomerId ON dbo.OrdersHeap (CustomerId);\nGO\nSELECT OrderId, OrderDate, Total FROM dbo.OrdersHeap WHERE CustomerId = 4242;</code></pre>\n<p>To list the heaps in a database:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS XML OFF;\nSET STATISTICS IO OFF;\n\nSELECT OBJECT_SCHEMA_NAME(i.object_id) AS schema_name, OBJECT_NAME(i.object_id) AS table_name\nFROM sys.indexes AS i\nWHERE i.type = 0 AND OBJECTPROPERTY(i.object_id, 'IsUserTable') = 1;</code></pre>\n<h3>Oracle: TABLE ACCESS BY INDEX ROWID</h3>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nEXPLAIN PLAN FOR\nSELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation                           | Name                | Rows  | Bytes | Cost (%CPU)| Time     |\n|   0 | SELECT STATEMENT                    |                     |    20 |   460 |    21   (0)| 00:00:01 |\n|   1 |  TABLE ACCESS BY INDEX ROWID BATCHED| ORDERS              |    20 |   460 |    21   (0)| 00:00:01 |\n|*  2 |   INDEX RANGE SCAN                  | ORDERS_CUSTOMER_IDX |    20 |       |     3   (0)| 00:00:01 |</code></pre>\n<p>Operation 2 finds the rowids in the index, operation 1 fetches each row from the table. <code>BATCHED</code> means Oracle sorts the rowids by block first, so neighbouring rows are fetched together.</p>\n<h3>PostgreSQL, MySQL and SQLite: index scan versus covering scan</h3>\n<p>These engines show the table visit in the name of the scan. PostgreSQL prints <code>Index Scan</code> (or a <code>Bitmap Heap Scan</code>) when it visits the table and <code>Index Only Scan</code> when it does not:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nEXPLAIN (ANALYZE, BUFFERS)\nSELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Bitmap Heap Scan on orders  (cost=4.59..84.54 rows=21 width=18) (actual time=0.029..0.055 rows=20.00 loops=1)\n  Recheck Cond: (customer_id = 4242)\n  Heap Blocks: exact=20\n  -&gt;  Bitmap Index Scan on orders_customer_idx  (cost=0.00..4.58 rows=21 width=0) (actual time=0.021..0.021 rows=20.00 loops=1)\n        Index Cond: (customer_id = 4242)</code></pre>\n<p>MySQL prints <code>Using index</code> in the <code>Extra</code> column when the index covers the query and leaves it out when InnoDB has to read the row from the primary key. In the tree format the two cases are <code>Covering index lookup</code> and <code>Index lookup</code>.</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nEXPLAIN FORMAT=TREE\nSELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;\n\nEXPLAIN FORMAT=TREE\nSELECT order_id FROM orders WHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Index lookup on orders using orders_customer_idx (customer_id=4242)  (cost=7 rows=20)\n-&gt; Covering index lookup on orders using orders_customer_idx (customer_id=4242)  (cost=3.02 rows=20)</code></pre>\n<p>The second query is covered by the same index because every InnoDB secondary index also stores the primary key columns.</p>\n<p>SQLite prints <code>USING INDEX</code> or <code>USING COVERING INDEX</code>:</p>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nEXPLAIN QUERY PLAN\nSELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\" data-role=\"output\"><code>`--SEARCH orders USING INDEX orders_customer_idx (customer_id=?)</code></pre>","fix_html":"<h3>Add the missing columns to the index</h3>\n<p>Put the columns the query reads into the index, so the index alone answers the query. SQL Server and PostgreSQL have an <code>INCLUDE</code> list for columns that are only returned, which keeps them out of the key:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId)\n    INCLUDE (OrderDate, Total)\n    WITH (DROP_EXISTING = ON);\nGO\nSET STATISTICS IO ON;\nGO\nSELECT OrderId, OrderDate, Total FROM dbo.Orders WHERE CustomerId = 4242;\nSELECT OrderId, OrderDate, Total FROM dbo.Orders WHERE CustomerId = 1;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 4, physical reads 0\nTable 'Orders'. Scan count 1, logical reads 147, physical reads 0</code></pre>\n<p>Both queries are now a single <code>Index Seek</code>. The small customer went from 64 page reads to 4, and the large one from a 2,579-page scan to 147.</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_customer_cover_idx ON orders (customer_id) INCLUDE (order_date, total);\n\nEXPLAIN (ANALYZE, BUFFERS)\nSELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Bitmap Heap Scan on orders  (cost=4.59..84.54 rows=21 width=18) (actual time=0.041..0.065 rows=20.00 loops=1)\n  Recheck Cond: (customer_id = 4242)\n  Heap Blocks: exact=20\n  -&gt;  Bitmap Index Scan on orders_customer_cover_idx  (cost=0.00..4.58 rows=21 width=0) (actual time=0.032..0.032 rows=20.00 loops=1)\n        Index Cond: (customer_id = 4242)</code></pre>\n<p>The plan has not changed. The query also returns <code>order_id</code>, which is not in the index: a PostgreSQL index does not carry the primary key, so the table is still visited. Add it to the <code>INCLUDE</code> list as well:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>DROP INDEX orders_customer_cover_idx;\nCREATE INDEX orders_customer_cover_idx ON orders (customer_id) INCLUDE (order_id, order_date, total);\n\nEXPLAIN (ANALYZE, BUFFERS)\nSELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Index Only Scan using orders_customer_cover_idx on orders  (cost=0.42..4.79 rows=21 width=18) (actual time=0.015..0.016 rows=20.00 loops=1)\n  Index Cond: (customer_id = 4242)\n  Heap Fetches: 0</code></pre>\n<p>A PostgreSQL index-only scan also depends on the visibility map; if <code>Heap Fetches</code> is not zero, see <a href=\"/sql-performance/index-only-scan-heap-fetches\">heap fetches in an index-only scan</a>.</p>\n<p>MySQL, SQLite and Oracle have no <code>INCLUDE</code> list. Append the columns to the key instead:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>CREATE INDEX orders_customer_cover_idx ON orders (customer_id, order_date, total);\n\nEXPLAIN FORMAT=TREE\nSELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Covering index lookup on orders using orders_customer_cover_idx (customer_id=4242)  (cost=3.04 rows=20)</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>CREATE INDEX orders_customer_cover_idx ON orders (customer_id, order_date, total);\n\nEXPLAIN QUERY PLAN\nSELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\" data-role=\"output\"><code>`--SEARCH orders USING COVERING INDEX orders_customer_cover_idx (customer_id=?)</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>CREATE INDEX orders_customer_cover_idx ON orders (customer_id, order_date, total, order_id);\n\nEXPLAIN PLAN FOR\nSELECT order_id, order_date, total FROM orders WHERE customer_id = 4242;\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation        | Name                      | Rows  | Bytes | Cost (%CPU)| Time     |\n|   0 | SELECT STATEMENT |                           |    20 |   460 |     3   (0)| 00:00:01 |\n|*  1 |  INDEX RANGE SCAN| ORDERS_CUSTOMER_COVER_IDX |    20 |   460 |     3   (0)| 00:00:01 |</code></pre>\n<p>The <a href=\"/sql-dialects/covering-index\">covering index page</a> compares the syntax across engines.</p>\n<h3>Ask for fewer columns</h3>\n<p>The lookup exists because of the select list. <code>SELECT *</code> can never be covered by a narrow index. If the code only uses three columns, select three columns, and an index that already exists may cover the query as it is.</p>\n<h3>Give a heap a clustered index</h3>\n<p>On SQL Server a heap makes every index lookup a <code>RID Lookup</code>. Unless the table is a staging table that is loaded and truncated, give it a clustered index, normally on the primary key:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE UNIQUE CLUSTERED INDEX CX_OrdersHeap ON dbo.OrdersHeap (OrderId);</code></pre>\n<h3>Do not cover everything</h3>\n<p>Every included column is stored again in the index and written again on every update of that column. Compare the sizes before you add five columns to an index:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SELECT pg_size_pretty(pg_relation_size('orders')) AS table_size,\n       pg_size_pretty(pg_relation_size('orders_customer_idx')) AS narrow_index,\n       pg_size_pretty(pg_relation_size('orders_customer_cover_idx')) AS covering_index;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>table_size | narrow_index | covering_index\n35 MB      | 3024 kB      | 15 MB</code></pre>\n<p>An index that includes most of the table's columns is a second copy of the table. Cover the two or three queries that run constantly, and leave the rest with their lookups.</p>\n<h3>When to leave the lookup alone</h3>\n<p>Leave it when the index returns few rows: a lookup for 20 rows costs a few dozen page reads. Leave it for queries that run rarely. Fix it when the lookup runs thousands of times per execution, when it is the most expensive operator in the plan, or when the optimizer switches to a full scan for some parameter values because the lookups would be too many.</p>","checklist_html":["Find the lookup: Key Lookup or RID Lookup (SQL Server), TABLE ACCESS BY INDEX ROWID (Oracle), a non-covering index scan elsewhere.","Read how many times it runs: the row count coming out of the index seek.","List the columns the lookup fetches (the Output List in SQL Server).","Check whether the query needs all of those columns; trim the select list first.","Add the remaining columns to the index: INCLUDE on SQL Server and PostgreSQL, key columns elsewhere.","Re-capture the plan and confirm a single seek or a covering scan, with fewer reads.","Compare index size before and after, and do not cover queries that run rarely."],"faqs":[{"question":"What is the difference between a Key Lookup and a RID Lookup?","answer":"Both fetch the rest of a row after a nonclustered index found it. A Key Lookup goes to the clustered index using the clustering key. A RID Lookup appears when the table is a heap, with no clustered index, and goes to the row's physical location."},{"question":"Why did SQL Server stop using my index and scan the table?","answer":"Because the number of rows it expects makes the lookups more expensive than one pass over the table. Each lookup is a separate read of the clustered index, so past a small share of the table the scan wins. A covering index removes the lookups and with them the tipping point."},{"question":"Should included columns go in the key or in INCLUDE?","answer":"Columns the query filters, joins or sorts on belong in the key. Columns that are only returned belong in INCLUDE on SQL Server and PostgreSQL: they are stored only in the leaf level and do not affect the order of the index. MySQL, SQLite and Oracle have no INCLUDE, so the columns are appended to the key."},{"question":"Does MySQL have key lookups?","answer":"Yes, but the plan does not draw them. InnoDB secondary indexes store the primary key, and a query that needs other columns reads the row from the primary key for each index entry. The plan shows Using index in the Extra column, or Covering index lookup in the tree format, only when that second read is avoided."},{"question":"Is a covering index always worth it?","answer":"No. It makes the index larger and every write to the included columns more expensive. It is worth it for queries that run often and return enough rows for the lookups to show up in the plan's cost."}],"plan_group":"Indexes and access paths","related_slugs":["index-only-scan-heap-fetches","full-table-scan","missing-index"]},"source_url":"https://sqlly.app/sql-performance/key-lookup","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/memory-pressure","corpus":"sql-performance","engine":null,"language":"en","title":"Memory pressure","description":"When a database runs out of cache, reads go to disk and everything slows. Measure the hit rates, size the caches for the working set, and avoid the classic mistakes.","body":{"slug":"memory-pressure","engines":["SQL Server","PostgreSQL","MySQL","Oracle"],"symptoms":["Memory pressure","Sudden slowdown","Slow query"],"h1":"Memory pressure","lede":"The database is slow and disk is busy: the working set does not fit in the cache. How to measure the hit rate on each engine, size the main caches correctly, and spot memory leaks vs undersizing.","symptom_html":"<p>Everything got slower at once, disk I/O spiked, and the plans did not change. That is memory pressure: the pages queries need are not in the buffer cache, so every read pays for disk. The fix is measurement first - 'more RAM' is only sometimes the answer.</p>","diagnosis_html":"<h3>SQL Server: buffer pool and memory clerks</h3>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT type, SUM(pages_kb) / 1024 AS mb\nFROM sys.dm_os_memory_clerks\nGROUP BY type\nORDER BY SUM(pages_kb) DESC;</code></pre>\n<p><code>MEMORYCLERK_SQLBUFFERPOOL</code> is the data cache. <code>CACHESTORE_SQLCP</code> (ad-hoc and prepared plans) growing to several gigabytes is plan cache bloat from unparameterized SQL, memory taken away from data pages; <code>CACHESTORE_OBJCP</code> is procedure and trigger plans. To see which databases hold the buffer pool:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT COUNT(*) / 128 AS cached_mb, DB_NAME(database_id) AS database_name\nFROM sys.dm_os_buffer_descriptors\nGROUP BY database_id\nORDER BY cached_mb DESC;</code></pre>\n<p>That view has one row per 8 KB page in memory, so on a server with hundreds of gigabytes it is slow; run it off-peak. Two more signals: Page Life Expectancy from <code>sys.dm_os_performance_counters</code> (<code>counter_name = 'Page life expectancy'</code>), read as a trend rather than against a fixed number, and queries waiting for workspace memory, which show up as <code>RESOURCE_SEMAPHORE</code> waits and as rows in <code>sys.dm_exec_query_memory_grants</code> with <code>granted_memory_kb IS NULL</code>.</p>\n<h3>PostgreSQL: buffers in the plan, cache stats in the view</h3>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, BUFFERS) SELECT ...;\n-- Buffers: shared hit=84            all pages found in shared_buffers\n-- Buffers: shared hit=7 read=4      4 pages fetched from the OS\n\nSELECT round(blks_hit * 100.0 / nullif(blks_hit + blks_read, 0), 2) AS hit_pct\nFROM pg_stat_database WHERE datname = current_database();</code></pre>\n<p>Persistent <code>read=</code> counts on a query that runs constantly are the direct evidence of pressure. Read the database-wide ratio with care: <code>blks_read</code> counts pages PostgreSQL asked the operating system for, and many of those come from the OS page cache, not the disk. A ratio in the low 90s on an OLTP database is worth investigating; confirm with OS disk metrics, or with <code>track_io_timing = on</code>, which adds I/O time to <code>EXPLAIN</code> and pg_stat_statements. The <code>pg_buffercache</code> extension (<code>CREATE EXTENSION pg_buffercache;</code>, superuser or <code>pg_monitor</code>) shows which tables and indexes occupy shared_buffers.</p>\n<h3>MySQL: the buffer pool counters</h3>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_read%';\n-- hit% = 1 - Innodb_buffer_pool_reads / Innodb_buffer_pool_read_requests</code></pre>\n<p><code>Innodb_buffer_pool_reads</code> counts reads InnoDB had to take from disk; both counters run from server start, so compare the change between two readings. If disk reads climb as a share of requests during the day, the pool no longer holds the working set. <code>sys.innodb_buffer_stats_by_table</code> shows which tables occupy the pool, but it walks every page and is expensive on a large pool.</p>\n<h3>Oracle: SGA and PGA in the dynamic views</h3>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>SELECT component, round(current_size / 1024 / 1024) AS mb\nFROM v$sga_dynamic_components\nWHERE current_size &gt; 0;\n\nSELECT size_for_estimate AS cache_mb, size_factor,\nestd_physical_read_factor\nFROM v$db_cache_advice\nWHERE name = 'DEFAULT'\nAND block_size = (SELECT value FROM v$parameter WHERE name = 'db_block_size')\nORDER BY size_for_estimate;\n\nSELECT round(pga_target_for_estimate / 1024 / 1024) AS pga_mb,\npga_target_factor, estd_pga_cache_hit_percentage, estd_overalloc_count\nFROM v$pga_target_advice\nORDER BY pga_target_for_estimate;</code></pre>\n<p>The buffer cache advisory estimates physical reads at other cache sizes: <code>size_factor = 1</code> is today's size, and if <code>estd_physical_read_factor</code> barely drops at 1.5 or 2, more cache will not help. In the PGA advisory, look at the row with <code>pga_target_factor = 1</code>: an <code>estd_pga_cache_hit_percentage</code> well below 100 means sorts and hashes are spilling to temp, and a non-zero <code>estd_overalloc_count</code> means the target is too small even for the minimum the workload needs. Sessions dominated by <code>User I/O</code> waits (<code>db file sequential read</code> for index blocks, <code>db file scattered read</code> for full scans) are the symptom: the cache is missing the blocks hot queries want.</p>","fix_html":"<p><strong>Size the main cache to the working set, not the database.</strong> Most databases have a hot subset far smaller than their total size. Measure it (the queries above show which tables and indexes actually hold cache), set the buffer pool or <code>shared_buffers</code> so that set fits, and leave the rest to the OS cache - PostgreSQL in particular expects hot pages to live in the OS cache too, not only in <code>shared_buffers</code>. The sizing statements, with example values to replace:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>EXEC sp_configure 'show advanced options', 1;\nRECONFIGURE;\nEXEC sp_configure 'max server memory', 12288;   -- MB; leave headroom for the OS\nRECONFIGURE;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>ALTER SYSTEM SET shared_buffers = '4GB';\n-- takes effect at the next restart</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>SET PERSIST innodb_buffer_pool_size = 12884901888;   -- 12 GB, in bytes</code></pre>\n<p><strong>Fix waste before adding RAM.</strong> On SQL Server, a plan cache full of single-use ad-hoc plans shrinks with <code>sp_configure 'optimize for ad hoc workloads', 1</code>, which caches only a small stub until a statement runs a second time; parameterizing the SQL fixes the cause. On PostgreSQL, a large <code>work_mem</code> multiplied by many concurrent sorts and hashes can exhaust RAM - size it for the concurrency you actually have, and raise it per session or per role for the reporting jobs that need it.</p>\n<p><strong>Check what else shares the box.</strong> A backup agent, an app server, or another instance on the same host competes for the same RAM. Set SQL Server's <code>max server memory</code> so the OS and other processes keep their headroom; the default (2,147,483,647 MB, effectively unlimited) lets SQL Server take nearly everything. Setup has offered a recommended value since SQL Server 2019, but it applies only when you accept it on the Memory tab, and instances upgraded in place keep the old default.</p>\n<p><strong>Reduce the working set itself.</strong> Narrowing the widest hot table, archiving old rows, and fixing the scans in the <a href=\"/sql-performance/index-not-used\">index guide</a> all shrink what the cache has to hold - sometimes enough to make the sizing question disappear. When a plan shows sorts spilling to disk that did not spill before, paste it into the <a href=\"/tools/query-plan-viewer\">query plan viewer</a>; the spilled operator is where the cache gave up.</p>\n<h3>When more cache will not help</h3>\n<p>Cache cannot fix a plan that reads too much: a query doing 100,000 logical reads to return 10 rows stays wasteful at any memory size, and the <a href=\"/sql-performance/index-not-used\">index guide</a> is the fix. Watch one trap on SQL Server: <code>max server memory</code> bounds only the buffer pool, not the plan cache and other clerks, so an instance whose memory clerks are dominated by <code>CACHESTORE_SQLCP</code> needs parameterized SQL, not more RAM. And on PostgreSQL, remember <code>blks_read</code> counts pages asked of the OS - many of which the OS page cache served from RAM - so confirm real disk pressure with OS metrics before buying memory.</p>","checklist_html":["Measure the cache hit rate for the engine (queries above) over a peak hour.","Find what actually holds cache: sys.dm_os_buffer_descriptors (SQL Server), the pg_buffercache extension, sys.innodb_buffer_stats_by_table (MySQL), v$db_cache_advice (Oracle).","Separate working set from waste: single-use plans in the SQL Server plan cache and an oversized work_mem are configuration problems, not a need for RAM.","Set the main cache to fit the measured working set with headroom.","Bound SQL Server memory with max server memory if anything else runs on the host.","Re-measure the hit rate the next peak: disk reads should fall to near-zero for hot paths.","If the working set genuinely does not fit, archive data or add RAM - in that order."],"faqs":[{"question":"Is a low page life expectancy always bad?","answer":"No. PLE drops whenever something reads a lot of new pages - an index rebuild, a big report, a restore - and climbs back afterwards. The old 300-second rule of thumb dates from servers with 4 GB of RAM and means little on a large buffer pool. On NUMA hardware, check the per-node values under Buffer Node as well. What matters is a persistently falling PLE on a server with steady I/O wait - that means the cache cannot hold the working set. Judge it alongside the I/O waits, never alone."},{"question":"How big should shared_buffers be on PostgreSQL?","answer":"The classic starting point is 25% of RAM on a dedicated database server, with the OS cache holding much of the rest - PostgreSQL reads through the OS cache anyway. The right number is the one that fits the measured working set; check the hit rate from pg_stat_database after each change instead of following folklore."},{"question":"Can work_mem cause out-of-memory crashes?","answer":"Yes. work_mem is a limit per sort or hash operation, not per query: a query with five sorts can use five times the setting, each parallel worker gets its own allowance, and hash operations may use work_mem x hash_mem_multiplier (2.0 by default since PostgreSQL 15). Multiply by concurrent sessions and a generous setting can exceed RAM. On Linux the OOM killer then kills a backend and the postmaster restarts every session; vm.overcommit_memory = 2 makes the failing query get an out-of-memory error instead."},{"question":"The hit rate is 99% but users still report slowness. Is memory still the problem?","answer":"Probably not. A 99% hit rate means the cache is doing its job; the slowness is in the remaining 1% (an unlucky scan), in lock waits, or in CPU-bound per-row work. Follow the slow query and blocking guides before touching memory sizing."},{"question":"Where does memory sizing interact with query plans?","answer":"Undersized memory forces sorts and hashes to spill to disk, which shows in plans as spill or temp-buffer operators and can be orders of magnitude slower. If plans suddenly show spills that were not there before, memory pressure changed the plan's cost - fix the memory or the query's sort size, and the plan returns to normal."}],"plan_group":null,"related_slugs":[]},"source_url":"https://sqlly.app/sql-performance/memory-pressure","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/missing-index","corpus":"sql-performance","engine":null,"language":"en","title":"Missing index suggestions in the plan","description":"SQL Server plans name the index the optimizer wanted and did not find. How to read the suggestion, check it against the DMVs, and decide whether to build it.","body":{"slug":"missing-index","engines":["SQL Server","SQLite"],"symptoms":["Bad index usage","Slow query"],"h1":"Missing index suggestions in the plan","lede":"SQL Server writes the index it wanted into the plan. How to read the suggestion, find the same request in the missing-index DMVs, turn it into an index that fits the ones you already have, and what the suggestion does not consider.","symptom_html":"<p>While SQL Server compiles a query it notes any index that would have made the chosen plan cheaper. The note travels with the plan: Management Studio prints it in green above the diagram, the plan XML carries it as a <code>MissingIndexes</code> element, and the <a href=\"/tools/query-plan-viewer\">query plan viewer</a> lists it as a finding with the <code>CREATE INDEX</code> statement written out.</p>\n<p>The suggestion is a fact about one query, not a recommendation for the table. It is worth reading every time and worth building only some of the time.</p>","diagnosis_html":"<h3>Read the suggestion in the plan</h3>\n<p>The examples use a shop schema with <code>dbo.Customers</code> (20,000 rows) and <code>dbo.Orders</code> (400,000 rows, 1% of them pending). Capture the actual plan of a query that filters on a column with no index:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS XML ON;\n\nSELECT c.Country, COUNT(*) AS Orders, SUM(o.Total) AS Total\nFROM dbo.Orders AS o\nJOIN dbo.Customers AS c ON c.CustomerId = o.CustomerId\nWHERE o.Status = 'pending'\nGROUP BY c.Country;</code></pre>\n<p>The plan XML contains the request:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>&lt;MissingIndexes&gt;\n  &lt;MissingIndexGroup Impact=\"73.5789\"&gt;\n    &lt;MissingIndex Database=\"[learnfx]\" Schema=\"[dbo]\" Table=\"[Orders]\"&gt;\n      &lt;ColumnGroup Usage=\"EQUALITY\"&gt;\n        &lt;Column Name=\"[Status]\" ColumnId=\"3\" /&gt;\n      &lt;/ColumnGroup&gt;\n      &lt;ColumnGroup Usage=\"INCLUDE\"&gt;\n        &lt;Column Name=\"[CustomerId]\" ColumnId=\"2\" /&gt;\n        &lt;Column Name=\"[Total]\" ColumnId=\"5\" /&gt;\n      &lt;/ColumnGroup&gt;\n    &lt;/MissingIndex&gt;\n  &lt;/MissingIndexGroup&gt;\n&lt;/MissingIndexes&gt;</code></pre>\n<p><code>Impact</code> is the optimizer's estimate of how much of the query's cost the index would remove, as a percentage. The columns come in three groups. <code>EQUALITY</code> columns are compared with <code>=</code> and go first in the index key. <code>INEQUALITY</code> columns are compared with a range and go after them. <code>INCLUDE</code> columns are only read, so they belong in the <code>INCLUDE</code> list, not in the key.</p>\n<p>A plan compiled as trivial carries no suggestion. A single-table query such as <code>SELECT OrderId FROM dbo.Orders WHERE Status = 'pending'</code> gets a trivial plan here and prints nothing, although the same index would help it.</p>\n<h3>Find the same request in the DMVs</h3>\n<p>Every suggestion is also recorded in the missing-index DMVs, with a count of how many times queries wanted that index. That count is what separates an index one report asked for once from an index the workload asks for all day.</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS XML OFF;\n\nSELECT d.statement AS table_name,\n       d.equality_columns, d.inequality_columns, d.included_columns,\n       s.user_seeks, s.avg_user_impact\nFROM sys.dm_db_missing_index_details AS d\nJOIN sys.dm_db_missing_index_groups AS g ON g.index_handle = d.index_handle\nJOIN sys.dm_db_missing_index_group_stats AS s ON s.group_handle = g.index_group_handle\nWHERE d.database_id = DB_ID()\nORDER BY s.user_seeks * s.avg_total_user_cost * s.avg_user_impact DESC;</code></pre>\n<p>For the query above it returns one row: table <code>[learnfx].[dbo].[Orders]</code>, equality columns <code>[Status]</code>, included columns <code>[CustomerId], [Total]</code>, one seek, impact 73.58.</p>\n<p>The <a href=\"/sql-snippets/missing-index-suggestions\">missing index suggestions snippet</a> is a fuller version of this query. The DMVs are not a permanent record: creating any index on the table removes the table's rows, and the counting starts again.</p>\n<h3>Compare it with the indexes the table already has</h3>\n<p>The optimizer does not look at existing indexes when it writes the suggestion. If the table has an index on <code>Status</code> alone, the plan still asks for a new index on <code>Status</code> with included columns, when widening the existing one is the better change:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX IX_Orders_Status ON dbo.Orders (Status);\nGO\nSET STATISTICS XML ON;\nGO\nSELECT c.Country, COUNT(*) AS Orders, SUM(o.Total) AS Total\nFROM dbo.Orders AS o\nJOIN dbo.Customers AS c ON c.CustomerId = o.CustomerId\nWHERE o.Status = 'pending'\nGROUP BY c.Country;\nGO\nSET STATISTICS XML OFF;</code></pre>\n<p>List what is there before you create anything. The <a href=\"/sql-snippets/list-table-indexes-columns\">index listing snippet</a> prints every index on a table with its key and included columns.</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT i.name AS index_name, c.name AS column_name,\n       ic.key_ordinal, ic.is_included_column\nFROM sys.indexes AS i\nJOIN sys.index_columns AS ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id\nJOIN sys.columns AS c ON c.object_id = ic.object_id AND c.column_id = ic.column_id\nWHERE i.object_id = OBJECT_ID('dbo.Orders')\nORDER BY i.index_id, ic.is_included_column, ic.key_ordinal;</code></pre>","fix_html":"<h3>Widen an existing index when one is close</h3>\n<p>When an existing index has the same leading key columns, rebuild it with the extra columns instead of adding a second index. <code>DROP_EXISTING</code> replaces the index in one statement:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX IX_Orders_Status ON dbo.Orders (Status)\n    INCLUDE (CustomerId, Total)\n    WITH (DROP_EXISTING = ON);\nGO\nSET STATISTICS XML ON;\nGO\nSELECT c.Country, COUNT(*) AS Orders, SUM(o.Total) AS Total\nFROM dbo.Orders AS o\nJOIN dbo.Customers AS c ON c.CustomerId = o.CustomerId\nWHERE o.Status = 'pending'\nGROUP BY c.Country;\nGO\nSET STATISTICS XML OFF;</code></pre>\n<p>The plan now seeks <code>IX_Orders_Status</code> for the 4,000 pending orders and the <code>MissingIndexes</code> element is gone.</p>\n<h3>Create the index when nothing is close</h3>\n<p>Build the key from the equality columns, then the inequality columns, and put the rest in <code>INCLUDE</code>. The suggestion lists the equality columns in table order, not in the best order for your workload: put first the column that other queries also filter on, so one index serves more than one query. Name the index yourself; the generated names in Management Studio say nothing about what the index is for.</p>\n<h3>Merge overlapping suggestions</h3>\n<p>A busy database produces many suggestions that differ only in their included columns. Building each one gives the table five indexes on the same key. Group the DMV rows by <code>equality_columns</code> and <code>inequality_columns</code>, build one index per group with the union of the included columns, and check the result against the <a href=\"/sql-snippets/duplicate-indexes\">duplicate index snippet</a>.</p>\n<h3>When to ignore the suggestion</h3>\n<p>Ignore it when the query runs rarely, when <code>user_seeks</code> in the DMV is small, when the table takes heavy writes and already has many indexes, or when the suggestion includes most of the table's columns (that index is a second copy of the table). The impact number counts only the saving for this query. It does not count the cost of maintaining the index on every insert, update and delete.</p>\n<h3>SQLite: ask the shell for a suggestion</h3>\n<p>SQLite plans carry no index advice, but the <code>sqlite3</code> command-line shell can produce it. <code>.expert</code> analyses the next statement and prints the index it would add and the plan that results, without creating anything:</p>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>.expert\nSELECT order_id, total FROM orders WHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\" data-role=\"output\"><code>CREATE INDEX orders_idx_38e08b36 ON orders(customer_id);\nSEARCH orders USING INDEX orders_idx_38e08b36 (customer_id=?)</code></pre>\n<p>For PostgreSQL, MySQL and Oracle plans, which do not print suggestions, start from the scan itself: the <a href=\"/sql-performance/full-table-scan\">full table scan page</a> shows how to work out the index from the plan.</p>","checklist_html":["Read the suggestion: equality columns, inequality columns, included columns and impact.","Look up the same request in sys.dm_db_missing_index_group_stats and note user_seeks.","List the table's existing indexes and look for one with the same leading key columns.","Widen that index with DROP_EXISTING, or create a new one with equality columns first.","Merge suggestions that share key columns into one index.","Re-capture the plan and confirm the seek and the drop in logical reads.","Check sys.dm_db_index_usage_stats after a week: an index with writes and no seeks should go."],"faqs":[{"question":"Why does my plan show no missing index although it scans a table?","answer":"The optimizer only records a suggestion during full optimization. Plans compiled as trivial, which includes many simple single-table queries, never carry one. Suggestions are also not produced for every plan shape, so the absence of a suggestion does not mean no index would help."},{"question":"Does the column order in the suggestion matter?","answer":"The order of the groups matters: equality columns first, then inequality columns, with included columns outside the key. The order inside the equality group is the order of the columns in the table and carries no meaning. Choose it yourself, usually with the column most other queries filter on first."},{"question":"Should I create every missing index SQL Server suggests?","answer":"No. Each suggestion is made for one query without regard to the indexes that exist or to write cost. Build the ones that many executions ask for, merge the ones that overlap, and prefer widening an existing index to adding a new one."},{"question":"What does the Impact percentage mean?","answer":"It is the estimated percentage by which the cost of that one query would fall if the index existed. It is an estimate from the optimizer's cost model, not a measurement, and it says nothing about how often the query runs. Multiply it by user_seeks from the DMV to rank suggestions."},{"question":"Do other databases print missing index suggestions?","answer":"Not in the plan. PostgreSQL, MySQL, Oracle and SQLite plans show the scan and leave the index to you. The sqlite3 shell has the .expert command, which proposes indexes for a statement."}],"plan_group":"Indexes and access paths","related_slugs":["full-table-scan","key-lookup","index-not-used"]},"source_url":"https://sqlly.app/sql-performance/missing-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/mysql","corpus":"sql-performance","engine":null,"language":"en","title":"MySQL query performance troubleshooting","description":"Diagnose slow MySQL queries with the slow query log, performance_schema digests and EXPLAIN ANALYZE, then fix full scans and buffer pool misses.","body":{"slug":"mysql","engines":["MySQL"],"symptoms":["Slow query","High CPU","Bad index usage"],"h1":"MySQL query performance troubleshooting","lede":"A method for slow MySQL queries: capture them with the slow log, rank them with performance_schema, read EXPLAIN ANALYZE, and fix what it shows.","symptom_html":"<p>MySQL is slow: a query takes seconds, the server runs hot, or the app times out at peak hours. On MySQL 8.0 and later, performance_schema is on by default and the sys schema is installed, so everything below works on a stock server. Changing global variables needs <code>SYSTEM_VARIABLES_ADMIN</code> (or the older <code>SUPER</code>); reading performance_schema needs SELECT on it.</p>","diagnosis_html":"<h3>Capture the offenders with the slow query log</h3>\n<p>The log records each slow statement with its real time, rows examined and rows sent:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>SET GLOBAL slow_query_log = 'ON';\nSET GLOBAL long_query_time = 0.5;\nSET GLOBAL log_queries_not_using_indexes = 'ON';\nSHOW VARIABLES LIKE 'slow_query_log_file';</code></pre>\n<p>Two catches: a new <code>long_query_time</code> only applies to connections opened after the change, and <code>SET GLOBAL</code> is lost on restart (use <code>SET PERSIST</code> to keep it). <code>log_queries_not_using_indexes</code> logs every unindexed statement however fast it was, so watch the file's growth on a busy server. Aggregate the file with <code>mysqldumpslow</code>, which ships with MySQL, or Percona's <code>pt-query-digest</code>. For a live ranking without the log, use the digest table:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>SELECT DIGEST_TEXT, COUNT_STAR,\nround(AVG_TIMER_WAIT / 1e12, 3) AS avg_seconds,\nround(SUM_TIMER_WAIT / 1e12, 1) AS total_seconds\nFROM performance_schema.events_statements_summary_by_digest\nORDER BY SUM_TIMER_WAIT DESC\nLIMIT 10;</code></pre>\n<p>Timer columns in performance_schema are in picoseconds, hence the <code>1e12</code>. Digests replace literals with <code>?</code>, so one row covers every run of the same statement shape; the counters run from server start or the last <code>TRUNCATE TABLE</code> on the table. The sys schema wraps the same data with friendlier names: <code>sys.statements_with_full_table_scans</code> and <code>sys.statements_with_temp_tables</code> list the usual suspects directly.</p>\n<h3>Read the plan with real timings</h3>\n<p>MySQL 8.0.18 and newer can run the statement for real:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN ANALYZE\nSELECT o.id, o.total, c.email\nFROM orders AS o JOIN customers AS c ON c.id = o.customer_id\nWHERE o.status = 'pending'\nAND o.created_at &gt;= NOW() - INTERVAL 7 DAY;</code></pre>\n<p>The tree shows, per iterator, the estimated cost and rows next to the actual time (first row..all rows, in milliseconds), rows and loops. Look for <code>Table scan on o</code> under a <code>Filter</code> whose actual rows are a small fraction of the scan's: that is MySQL reading the whole table to keep a handful of rows. Multiply time and rows by <code>loops</code> for anything inside a nested loop. On servers older than 8.0.18, plain <code>EXPLAIN</code> plus <code>SHOW WARNINGS</code> still shows the chosen keys, the <code>rows</code> estimate and the rewritten query. MariaDB spells its equivalent <code>ANALYZE</code>: <code>ANALYZE SELECT ...</code> runs the statement and prints the plan annotated with actual times and rows (MariaDB 10.1 and later), and <code>ANALYZE FORMAT=JSON SELECT ...</code> adds the detailed JSON view. Format both the query and the plan output with the <a href=\"/tools/sql-formatter\">SQL formatter</a> when they arrive as one long line from the log.</p>\n<h3>Check the buffer pool hit rate</h3>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_read%';</code></pre>\n<p>Divide <code>Innodb_buffer_pool_reads</code> (reads InnoDB had to take from disk) by <code>Innodb_buffer_pool_read_requests</code> (logical reads). Both count from server start, so take two readings a few minutes apart and divide the differences. If disk reads stay above a fraction of a percent of requests on a busy server, the working set does not fit in the pool - the <a href=\"/sql-performance/memory-pressure\">memory pressure guide</a> covers the sizing. If a query blocks or deadlocks rather than runs slow, the <a href=\"/sql-performance/blocking-deadlocks\">blocking and deadlocks guide</a> takes over from here.</p>","fix_html":"<p><strong>Index the columns the scan touches.</strong> InnoDB uses the leftmost prefix of an index, so put the equality column first and the range column last, and append the selected columns to skip the table lookups:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>ALTER TABLE orders\nADD INDEX idx_orders_status_created (status, created_at, customer_id, total);</code></pre>\n<p><strong>Refresh the optimizer's statistics</strong> if the plan changed for no reason, and re-run EXPLAIN ANALYZE afterwards:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>ANALYZE TABLE orders;</code></pre>\n<p><strong>Keep the working set in memory.</strong> If the hit rate is poor, raise <code>innodb_buffer_pool_size</code> (on a dedicated server, commonly 60-75% of RAM). It has been resizable online with <code>SET GLOBAL</code> since MySQL 5.7.5; the resize runs in the background in chunks of <code>innodb_buffer_pool_chunk_size</code>, and you still need <code>SET PERSIST</code> or the config file to keep it after a restart.</p>\n<p><strong>Let unused indexes go.</strong> Every index costs something on every write; <code>sys.schema_unused_indexes</code> lists indexes with no recorded use since the server started. A server restarted last week has not seen your month-end jobs yet, so check uptime before dropping anything. MySQL 8.0 can make an index invisible (<code>ALTER TABLE orders ALTER INDEX idx_name INVISIBLE;</code>) to test the drop without losing the index.</p>\n<h3>When none of this is the problem</h3>\n<p>A query that blocks rather than runs slow belongs to the <a href=\"/sql-performance/blocking-deadlocks\">blocking guide</a>, not to this page. The first minutes after a restart are slow everywhere because the buffer pool is cold; measure again once it has warmed, or the numbers will condemn a healthy plan. Disk time spent on a backup or a binlog purge is not query time either. And on a replicated setup, replica lag is often read as \"the query is slow\" when it finished instantly on the primary - check <code>SHOW REPLICA STATUS</code> before tuning anything.</p>","checklist_html":["Turn on the slow query log with long_query_time = 0.5 and reconnect so the new threshold applies.","Aggregate the log (mysqldumpslow or pt-query-digest) or read the top digests from performance_schema.","EXPLAIN ANALYZE the worst query; note every full table scan and the rows it processes.","Check the index exists and its leftmost prefix matches the WHERE clause order.","ANALYZE TABLE the hot tables if the plan looks wrong for the data you know.","Add one covering index with equality columns first and range columns last.","Compute the buffer pool hit rate; if disk reads dominate, size the pool to the working set.","Review sys.schema_unused_indexes after a full business cycle of uptime; make a candidate INVISIBLE before dropping it."],"faqs":[{"question":"The query is fast in my test client and slow in production. Why?","answer":"Plans depend on data volume and buffer pool warmth, not just on the SQL. In production the table may be a hundred times larger, the working set may not fit in memory, or the cached plan was built for different statistics. EXPLAIN ANALYZE on the production server is the only measurement that counts."},{"question":"Does log_queries_not_using_indexes slow the server down?","answer":"The logging itself is cheap, but on a server with many unindexed statements the log file can grow to gigabytes an hour, and that I/O is not free. Turn it on to hunt for a day, aggregate, then turn it off until the next hunt."},{"question":"Why doesn't MySQL use my index on created_at?","answer":"The most common reasons: the predicate wraps the column in a function (DATE(created_at) = ...), the index's leftmost column is not in the predicate, or the optimizer estimates the range covers too much of the table and a scan is cheaper. Compare the estimate in EXPLAIN's rows column with the table's actual row count before blaming the optimizer."},{"question":"How big should innodb_buffer_pool_size be?","answer":"Big enough to hold the hot working set - the pages actually read repeatedly - which is usually far smaller than the whole database. Watch the hit rate from Innodb_buffer_pool_read%: if reads from disk are rare in steady state, the pool is big enough; raising it further only helps writes and scans marginally."},{"question":"What is the fastest way to find queries burning CPU?","answer":"Order performance_schema.events_statements_summary_by_digest by SUM_TIMER_WAIT and look at SUM_ROWS_EXAMINED next to SUM_ROWS_SENT. Most MySQL CPU goes into reading and filtering rows, so a digest that examines millions of rows to send a handful is the usual culprit. sys.statements_with_full_table_scans lists the same offenders - see the high CPU guide for the full method."}],"plan_group":null,"related_slugs":[]},"source_url":"https://sqlly.app/sql-performance/mysql","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/non-sargable-predicates","corpus":"sql-performance","engine":null,"language":"en","title":"Non-sargable predicates","description":"A function or calculation around a column stops the index from being searched. How the plan shows it on five engines and how to rewrite the filter.","body":{"slug":"non-sargable-predicates","engines":["PostgreSQL","MySQL","SQL Server","Oracle","SQLite"],"symptoms":["Bad index usage","Slow query"],"h1":"Non-sargable predicates","lede":"The column is indexed, but the filter wraps it in a function, a calculation or a leading wildcard, so the index cannot be searched. How each engine's plan shows that, how to rewrite the filter as a range, and when to index the expression instead.","symptom_html":"<p>An index is sorted by the values of its columns. The engine can search it for <code>order_date &gt;= '2024-03-01'</code> because it knows where that value sits in the order. It cannot search it for <code>date(order_date) = '2024-03-01'</code>, because the index is not sorted by the result of the function. It has to compute the function for every row and compare afterwards. A filter the index can search is called sargable; one it cannot is non-sargable.</p>\n<p>In the plan the condition moves from the place where the index is searched to the place where rows are filtered: <code>Filter</code> instead of <code>Index Cond</code> in PostgreSQL, <code>Predicate</code> instead of <code>Seek Predicate</code> in SQL Server, <code>filter</code> instead of <code>access</code> in Oracle, a full scan in MySQL and SQLite. The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> points at the predicate. The examples use a shop schema with 400,000 orders, 480 per day, and an index on the order date.</p>","diagnosis_html":"<h3>A function around the column</h3>\n<p>All five examples ask for the orders of one day by converting the timestamp to a date.</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_date_idx ON orders (order_date);\n\nEXPLAIN (ANALYZE, BUFFERS)\nSELECT order_id, total FROM orders WHERE order_date::date = DATE '2024-03-01';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>-&gt;  Parallel Seq Scan on orders  (cost=0.00..6982.00 rows=833 width=10) (actual time=1.270..6.103 rows=160.00 loops=3)\n      Filter: ((order_date)::date = '2024-03-01'::date)\n      Rows Removed by Filter: 133173</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>CREATE INDEX orders_date_idx ON orders (order_date);\n\nEXPLAIN FORMAT=TREE\nSELECT order_id, total FROM orders WHERE DATE(order_date) = '2024-03-01';</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Filter: (cast(orders.order_date as date) = '2024-03-01')  (cost=40184 rows=398228)\n    -&gt; Table scan on orders  (cost=40184 rows=398228)</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX IX_Orders_OrderDate ON dbo.Orders (OrderDate) INCLUDE (Total);\nGO\nSET STATISTICS IO ON;\nSET STATISTICS XML ON;\nGO\nSELECT OrderId, Total FROM dbo.Orders WHERE CONVERT(char(10), OrderDate, 120) = '2024-03-01';</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 1250, physical reads 0</code></pre>\n<p>The SQL Server plan is an <code>Index Scan</code>: it reads all 400,000 entries of the index and tests the expression, which appears under <code>Predicate</code>, on each one.</p>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>CREATE INDEX orders_date_idx ON orders (order_date);\n\nEXPLAIN PLAN FOR\nSELECT order_id, total FROM orders WHERE TRUNC(order_date) = DATE '2024-03-01';\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation         | Name   | Rows  | Bytes | Cost (%CPU)| Time     |\n|   0 | SELECT STATEMENT  |        |  4000 | 72000 |   655   (2)| 00:00:01 |\n|*  1 |  TABLE ACCESS FULL| ORDERS |  4000 | 72000 |   655   (2)| 00:00:01 |</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>CREATE INDEX orders_date_idx ON orders (order_date);\n\nEXPLAIN QUERY PLAN\nSELECT order_id, total FROM orders WHERE date(order_date) = '2024-03-01';</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\" data-role=\"output\"><code>`--SCAN orders</code></pre>\n<h3>A calculation on the column</h3>\n<p>Arithmetic has the same effect as a function. The engine does not solve the equation for you:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_total_idx ON orders (total);\n\nEXPLAIN SELECT order_id FROM orders WHERE total * 2 &gt; 1998;\n\nEXPLAIN SELECT order_id FROM orders WHERE total &gt; 999;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Seq Scan on orders  (cost=0.00..10482.00 rows=133333 width=4)\n  Filter: ((total * '2'::numeric) &gt; '1998'::numeric)\nIndex Scan using orders_total_idx on orders  (cost=0.42..8.44 rows=1 width=4)\n  Index Cond: (total &gt; '999'::numeric)</code></pre>\n<h3>A pattern that starts with a wildcard</h3>\n<p><code>LIKE 'R4242%'</code> is a range in the index: everything from <code>R4242</code> up to <code>R4243</code>. <code>LIKE '%4242'</code> has no starting point, so every value is tested.</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>CREATE INDEX orders_reference_idx ON orders (reference);\n\nEXPLAIN SELECT order_id FROM orders WHERE reference LIKE 'R4242%'\\G\n\nEXPLAIN SELECT order_id FROM orders WHERE reference LIKE '%4242'\\G</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code> type: range\n  key: orders_reference_idx\n rows: 11\nExtra: Using where; Using index\n type: index\n  key: orders_reference_idx\n rows: 398228\nExtra: Using where; Using index</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX IX_Orders_Reference ON dbo.Orders (Reference);\nGO\nSELECT OrderId FROM dbo.Orders WHERE Reference LIKE 'R4242%';\nSELECT OrderId FROM dbo.Orders WHERE Reference LIKE '%4242';</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 3, physical reads 0\nTable 'Orders'. Scan count 1, logical reads 1039, physical reads 0</code></pre>\n<p>The first query is an <code>Index Seek</code> that reads 3 pages, the second an <code>Index Scan</code> of the same index that reads all of it.</p>\n<p>In PostgreSQL an ordinary index serves a prefix pattern only when the column uses the <code>C</code> collation. With any other collation, declare the index with <code>text_pattern_ops</code> (<code>varchar_pattern_ops</code> for a <code>varchar</code> column):</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_reference_idx ON orders (reference);\nEXPLAIN SELECT order_id FROM orders WHERE reference LIKE 'R4242%';\n\nCREATE INDEX orders_reference_pattern_idx ON orders (reference varchar_pattern_ops);\nEXPLAIN SELECT order_id FROM orders WHERE reference LIKE 'R4242%';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>  -&gt;  Parallel Seq Scan on orders  (cost=0.00..6565.33 rows=17 width=4)\n        Filter: ((reference)::text ~~ 'R4242%'::text)\nIndex Scan using orders_reference_pattern_idx on orders  (cost=0.42..8.44 rows=40 width=4)\n  Index Cond: (((reference)::text ~&gt;=~ 'R4242'::text) AND ((reference)::text ~&lt;~ 'R4243'::text))\n  Filter: ((reference)::text ~~ 'R4242%'::text)</code></pre>","fix_html":"<h3>Rewrite the filter as a range on the bare column</h3>\n<p>Leave the column alone and move the work to the other side of the comparison. One day is everything from midnight up to, but not including, the next midnight:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, BUFFERS)\nSELECT order_id, total FROM orders\nWHERE order_date &gt;= '2024-03-01' AND order_date &lt; '2024-03-02';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Index Scan using orders_date_idx on orders  (cost=0.42..1269.04 rows=469 width=10) (actual time=0.017..0.074 rows=480.00 loops=1)\n  Index Cond: ((order_date &gt;= '2024-03-01 00:00:00'::timestamp without time zone) AND (order_date &lt; '2024-03-02 00:00:00'::timestamp without time zone))\n  Buffers: shared hit=322 read=4</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN FORMAT=TREE\nSELECT order_id, total FROM orders\nWHERE order_date &gt;= '2024-03-01' AND order_date &lt; '2024-03-02';</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Index range scan on orders using orders_date_idx over ('2024-03-01 00:00:00' &lt;= order_date &lt; '2024-03-02 00:00:00'), with index condition: ((orders.order_date &gt;= TIMESTAMP'2024-03-01 00:00:00') and (orders.order_date &lt; TIMESTAMP'2024-03-02 00:00:00'))  (cost=216 rows=480)</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT OrderId, Total FROM dbo.Orders\nWHERE OrderDate &gt;= '2024-03-01' AND OrderDate &lt; '2024-03-02';</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 5, physical reads 0</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>EXPLAIN PLAN FOR\nSELECT order_id, total FROM orders\nWHERE order_date &gt;= DATE '2024-03-01' AND order_date &lt; DATE '2024-03-02';\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation                           | Name            | Rows  | Bytes | Cost (%CPU)| Time     |\n|   0 | SELECT STATEMENT                    |                 |   481 |  8658 |     7   (0)| 00:00:01 |\n|   1 |  TABLE ACCESS BY INDEX ROWID BATCHED| ORDERS          |   481 |  8658 |     7   (0)| 00:00:01 |\n|*  2 |   INDEX RANGE SCAN                  | ORDERS_DATE_IDX |   481 |       |     4   (0)| 00:00:01 |</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>EXPLAIN QUERY PLAN\nSELECT order_id, total FROM orders\nWHERE order_date &gt;= '2024-03-01' AND order_date &lt; '2024-03-02';</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\" data-role=\"output\"><code>`--SEARCH orders USING INDEX orders_date_idx (order_date&gt;? AND order_date&lt;?)</code></pre>\n<p>Use a half-open range (<code>&gt;=</code> and <code>&lt;</code>), not <code>BETWEEN</code> with <code>23:59:59</code>, which misses rows in the last second on columns with fractional seconds. The <a href=\"/sql-dialects/timestamp-range-filter\">timestamp range filter page</a> has the pattern for every engine, and <a href=\"/sql-dialects/extract-part-sargable\">sargable date parts</a> covers year and month filters.</p>\n<h3>SQL Server: a cast to date is the exception</h3>\n<p>SQL Server can seek an index through <code>CAST(column AS date)</code> on a date-and-time column. It converts the cast into a range itself:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT OrderId, Total FROM dbo.Orders WHERE CAST(OrderDate AS date) = '2024-03-01';</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 7, physical reads 0</code></pre>\n<p>Do not rely on it for other functions. <code>YEAR()</code>, <code>CONVERT</code> to a string, <code>DATEADD</code> or <code>DATEDIFF</code> around the column all scan.</p>\n<h3>Index the expression when you cannot change the query</h3>\n<p>If the query comes from a tool or an ORM, build an index on the expression. The query text must use the same expression as the index.</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_date_day_idx ON orders ((order_date::date));\nANALYZE orders;\n\nEXPLAIN SELECT order_id, total FROM orders WHERE order_date::date = DATE '2024-03-01';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Index Scan using orders_date_day_idx on orders  (cost=0.42..1290.96 rows=476 width=10)\n  Index Cond: ((order_date)::date = '2024-03-01'::date)</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>CREATE INDEX orders_date_day_idx ON orders ((DATE(order_date)));\n\nEXPLAIN FORMAT=TREE\nSELECT order_id, total FROM orders WHERE DATE(order_date) = '2024-03-01';</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Index lookup on orders using orders_date_day_idx (cast(order_date as date)='2024-03-01')  (cost=168 rows=480)</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>CREATE INDEX orders_date_day_idx ON orders (TRUNC(order_date));\n\nEXPLAIN PLAN FOR\nSELECT order_id, total FROM orders WHERE TRUNC(order_date) = DATE '2024-03-01';\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation                           | Name                | Rows  | Bytes | Cost (%CPU)| Time     |\n|   0 | SELECT STATEMENT                    |                     |   480 |  9120 |     8   (0)| 00:00:01 |\n|   1 |  TABLE ACCESS BY INDEX ROWID BATCHED| ORDERS              |   480 |  9120 |     8   (0)| 00:00:01 |\n|*  2 |   INDEX RANGE SCAN                  | ORDERS_DATE_DAY_IDX |   480 |       |     4   (0)| 00:00:01 |</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>CREATE INDEX orders_date_day_idx ON orders (date(order_date));\n\nEXPLAIN QUERY PLAN\nSELECT order_id, total FROM orders WHERE date(order_date) = '2024-03-01';</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\" data-role=\"output\"><code>`--SEARCH orders USING INDEX orders_date_day_idx (&lt;expr&gt;=?)</code></pre>\n<p>SQL Server has no expression indexes. Add a computed column and index that; the optimizer matches the expression in the query to the computed column:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>ALTER TABLE dbo.Orders ADD OrderDay AS CONVERT(char(10), OrderDate, 120);\nGO\nCREATE INDEX IX_Orders_OrderDay ON dbo.Orders (OrderDay) INCLUDE (Total);\nGO\nSELECT OrderId, Total FROM dbo.Orders WHERE CONVERT(char(10), OrderDate, 120) = '2024-03-01';</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 6, physical reads 0</code></pre>\n<p>The <a href=\"/sql-dialects/expression-index\">expression index page</a> lists the syntax and limits per engine.</p>\n<h3>PostgreSQL: a trigram index for patterns that start with a wildcard</h3>\n<p>No rewrite turns <code>LIKE '%4242'</code> into a range. PostgreSQL's <code>pg_trgm</code> extension indexes every three-character fragment of the text, which lets it search for a pattern anywhere in the value:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE EXTENSION IF NOT EXISTS pg_trgm;\nCREATE INDEX orders_reference_trgm_idx ON orders USING gin (reference gin_trgm_ops);\n\nEXPLAIN (ANALYZE)\nSELECT order_id FROM orders WHERE reference LIKE '%4242';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Bitmap Heap Scan on orders  (cost=34.51..183.67 rows=40 width=4) (actual time=0.068..0.108 rows=40.00 loops=1)\n  Recheck Cond: ((reference)::text ~~ '%4242'::text)\n  Rows Removed by Index Recheck: 1\n  Heap Blocks: exact=41\n  -&gt;  Bitmap Index Scan on orders_reference_trgm_idx  (cost=0.00..34.50 rows=40 width=0) (actual time=0.060..0.060 rows=41.00 loops=1)\n        Index Cond: ((reference)::text ~~ '%4242'::text)</code></pre>\n<p>On the other engines, a search inside a string needs a full-text index or a different design, such as storing the part you search for in its own column.</p>\n<h3>When to leave it alone</h3>\n<p>Leave it when the table is small, when another condition in the same query already narrows the rows through an index, or when the predicate keeps most of the table anyway. A function on the constant side of the comparison is never a problem: <code>order_date &gt;= CURRENT_DATE - 7</code> is computed once, not per row.</p>","checklist_html":["Find the condition in the plan: is it searched (Index Cond, Seek Predicate, access) or filtered (Filter, Predicate, filter)?","Look for a function, cast, calculation or leading wildcard around the column.","Rewrite it as a comparison or half-open range on the bare column.","If the query cannot change, index the expression (computed column on SQL Server).","For patterns starting with %, use a trigram index in PostgreSQL or a full-text index.","Re-capture the plan and confirm the condition is now part of the index search."],"faqs":[{"question":"What does sargable mean?","answer":"It is short for search argument able: a condition the engine can answer by searching an index instead of testing every row. column = value, column > value and column LIKE 'prefix%' are sargable. A function or calculation around the column usually is not."},{"question":"Does a function on the value side hurt?","answer":"No. order_date >= CURRENT_DATE - 7 applies the function to a constant, which is computed once before the index is searched. Only an expression around the column forces the engine to evaluate it for every row."},{"question":"Is BETWEEN sargable?","answer":"Yes. BETWEEN on a bare column is a range the index can search. For timestamps a half-open range with >= and < is safer, because BETWEEN includes the upper bound and an end value like 23:59:59 misses fractional seconds."},{"question":"Why does LIKE 'abc%' not use my index in PostgreSQL?","answer":"A default btree index supports prefix patterns only under the C collation. For other collations create the index with text_pattern_ops or varchar_pattern_ops, which sorts the values in a way that matches LIKE."},{"question":"Is WHERE CAST(col AS date) = ... always a scan?","answer":"On most engines it is unless you index the expression. SQL Server is the exception for a cast from a date-and-time type to date: it rewrites the cast into a range and seeks the index."}],"plan_group":"Indexes and access paths","related_slugs":["implicit-conversion","full-table-scan","index-not-used"]},"source_url":"https://sqlly.app/sql-performance/non-sargable-predicates","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/oracle","corpus":"sql-performance","engine":null,"language":"en","title":"Oracle query performance troubleshooting","description":"Diagnose slow Oracle queries with V$SESSION, V$SQLSTATS, ASH and DBMS_XPLAN actual plans, then fix logical reads, statistics and SGA pressure.","body":{"slug":"oracle","engines":["Oracle"],"symptoms":["Slow query","High CPU","Bad index usage","Memory pressure"],"h1":"Oracle query performance troubleshooting","lede":"A method for slow Oracle queries: see what sessions wait on, find the expensive SQL in V$SQLSTATS or ASH, get the actual plan from DBMS_XPLAN, then fix the access path or the statistics.","symptom_html":"<p>A query is slow on Oracle, or the instance is busy and nobody knows why. Oracle records what every session is waiting on, so the diagnosis is a matter of reading the right views in order. Two things to know first: the <code>V$</code> views need <code>SELECT_CATALOG_ROLE</code> or <code>SELECT ANY DICTIONARY</code>, and Active Session History and AWR are part of the Diagnostics Pack, a separately licensed option on Enterprise Edition. The ASH queries below are marked; everything else is free to use.</p>","diagnosis_html":"<h3>See what sessions are waiting on right now</h3>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>SELECT sid, username, sql_id,\nCASE WHEN state = 'WAITING' THEN event ELSE 'ON CPU' END AS activity,\nCASE WHEN state = 'WAITING' THEN wait_class END AS wait_class,\nround(CASE WHEN state = 'WAITING' THEN wait_time_micro\nELSE time_since_last_wait_micro END / 1e6, 1) AS seconds\nFROM v$session\nWHERE type = 'USER' AND status = 'ACTIVE'\nORDER BY seconds DESC;</code></pre>\n<p>The <code>CASE</code> matters: when <code>state</code> is anything other than <code>WAITING</code>, the session is on CPU and <code>event</code> still shows its <em>previous</em> wait, which misleads anyone reading the raw columns. Among the waits, <code>wait_class</code> sorts the problem: <code>User I/O</code> (<code>db file sequential read</code>, <code>db file scattered read</code>) is reads from disk, <code>Application</code> is mostly row locks, <code>Concurrency</code> is buffer busy waits and latches, <code>Commit</code> is <code>log file sync</code> on commit. A session waiting on <code>enq: TX - row lock contention</code> is blocked, not slow - the <a href=\"/sql-performance/blocking-deadlocks\">blocking and deadlocks guide</a> picks that up.</p>\n<h3>Sample the recent past with ASH (Diagnostics Pack)</h3>\n<p>Active Session History samples every active session once a second into a memory buffer that typically holds the last hour or so, depending on how busy the instance is:</p>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>SELECT sql_id, sql_plan_hash_value,\nCOUNT(*) AS samples,\nround(RATIO_TO_REPORT(COUNT(*)) OVER () * 100) AS pct\nFROM v$active_session_history\nWHERE sample_time &gt; SYSTIMESTAMP - INTERVAL '15' MINUTE\nGROUP BY sql_id, sql_plan_hash_value\nORDER BY samples DESC\nFETCH FIRST 10 ROWS ONLY;</code></pre>\n<p>Each sample is roughly one second of someone's wait or CPU, so the count is a workload profile: the SQL with the most samples owns the problem. Add <code>session_state</code> and <code>event</code> to the GROUP BY to see whether it was burning CPU or waiting. For older incidents, <code>dba_hist_active_sess_history</code> keeps one in ten samples for the AWR retention period (8 days by default).</p>\n<h3>Get the real plan with actual row counts</h3>\n<p>Run the query once with the gather hint, then read the plan it produced in the same session. In SQL*Plus, <code>SET SERVEROUTPUT OFF</code> first; otherwise <code>DISPLAY_CURSOR(NULL, NULL)</code> shows the plan of the DBMS_OUTPUT call SQL*Plus runs after your query:</p>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>SELECT /*+ gather_plan_statistics */ o.order_id, c.cust_name\nFROM orders o JOIN customers c ON c.customer_id = o.customer_id\nWHERE o.status = 'PENDING';\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(NULL, NULL, 'ALLSTATS LAST'));</code></pre>\n<p>The <code>A-Rows</code> column is actual rows; compare it with <code>E-Rows</code> on every line, remembering that E-Rows is per execution of the line and A-Rows is the total across all its <code>Starts</code>. Where actual dwarfs estimated, the optimizer guessed wrong - fix statistics before anything else. <code>Buffers</code> shows the logical reads, the number that tracks CPU and I/O cost. A note saying <code>dynamic statistics used</code> usually means a table in the query has no statistics at all. Format the SQL with the <a href=\"/tools/sql-formatter\">SQL formatter</a> and paste the plan into the <a href=\"/tools/query-plan-viewer\">query plan viewer</a> to read it without SQL Developer open.</p>\n<h3>Rank the SQL that reads the most (no pack needed)</h3>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>SELECT sql_id, executions, buffer_gets,\nround(buffer_gets / executions) AS gets_per_exec,\nround(cpu_time / 1e6, 1) AS cpu_seconds,\nround(elapsed_time / 1e6, 1) AS elapsed_seconds\nFROM v$sqlstats\nWHERE executions &gt; 0\nORDER BY buffer_gets DESC\nFETCH FIRST 10 ROWS ONLY;</code></pre>\n<p>The figures are cumulative while the statement stays in the shared pool, and times are in microseconds. <code>FETCH FIRST</code> needs Oracle 12c or later; on 11g wrap the query and filter on <code>ROWNUM</code>. Look up the text of any <code>sql_id</code> in <code>v$sqlstats.sql_fulltext</code>.</p>","fix_html":"<p><strong>Fix the statistics where estimates lie.</strong> The automatic statistics job (nightly maintenance window) covers most tables, and with the default <code>method_opt</code> it builds histograms on columns it has seen used in predicates. Tables loaded in bulk after the job ran, and skewed columns it missed, need a manual gather:</p>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>EXEC DBMS_STATS.GATHER_TABLE_STATS(USER, 'ORDERS', method_opt =&gt; 'FOR COLUMNS status SIZE 254');</code></pre>\n<p><strong>Index the path the plan walks.</strong> If the plan does a full scan on a big table for a selective predicate, add the index on the predicate columns and confirm the plan switches to an index range scan with far fewer buffers.</p>\n<p><strong>Reduce logical reads on hot statements.</strong> The SQL with the most buffer gets is where CPU and I/O both come from; covering indexes (add the selected columns) and rewrites that stop fetching the same rows repeatedly are the usual wins. The <a href=\"/sql-performance/high-cpu\">high CPU guide</a> continues from here.</p>\n<p><strong>Check memory before resizing.</strong> If the waits are dominated by User I/O, ask the buffer cache advisory how much a bigger cache would save before touching <code>sga_target</code> - the <a href=\"/sql-performance/memory-pressure\">memory pressure guide</a> covers <code>v$db_cache_advice</code> and the PGA advisory.</p>\n<h3>When the usual fixes do not apply</h3>\n<p>A full table scan is often the right answer on Oracle: with multiblock reads, scanning a large share of the table beats thousands of single-block index probes, so do not add an index just because the word FULL appears. Decide on logical reads per row returned, not on the operator's name. Two cautions on the diagnostics themselves: ASH and AWR samples consume resources of their own and need the Diagnostics Pack license, so on an unlicensed system stay with <code>v$session</code> and <code>v$sqlstats</code>; and a manual <code>GATHER_TABLE_STATS</code> on the biggest table runs long and competes with the workload - gather the hot skewed columns instead, or let the nightly maintenance window do the whole table.</p>","checklist_html":["Query v$session and name what active sessions are doing: ON CPU or the dominant wait_class.","With the Diagnostics Pack, sample the last 15 minutes of ASH; without it, rank v$sqlstats by elapsed time.","Run the top SQL with /*+ gather_plan_statistics */ and DISPLAY_CURSOR ALLSTATS LAST.","Compare A-Rows with E-Rows per plan line; refresh statistics where they diverge.","Rank v$sqlstats by buffer_gets and target the leader.","Add or extend the index the plan is missing; confirm the plan changed and buffers dropped.","Check DBA_INDEX_USAGE (12.2+) over a full business cycle before dropping any 'unused' index."],"faqs":[{"question":"What is the difference between ASH and AWR?","answer":"ASH samples which sessions were active and what they waited on, every second, in a memory buffer that covers roughly the last hour - use it to find the SQL that owned a recent slowdown. AWR takes a workload snapshot (SQL stats, system stats and every tenth ASH sample) every hour and keeps it for 8 days by default - use it to compare periods. ASH answers 'what just happened', AWR answers 'what changed between last week and now'."},{"question":"Do I need the Diagnostics or Tuning Pack for any of this?","answer":"Partly. v$session, v$sqlstats, v$sql and DBMS_XPLAN.DISPLAY_CURSOR are part of the database and need no extra license. v$active_session_history, the DBA_HIST views and AWR reports belong to the Diagnostics Pack, which is licensed separately on Enterprise Edition and not available on Standard Edition; the Tuning Pack adds SQL Tuning Advisor and SQL Monitoring. The control_management_pack_access parameter shows what the instance is set to allow, but setting it does not grant a license. Polling v$session and diffing v$sqlstats covers most of what ASH tells you."},{"question":"The plan has a full table scan - is that automatically wrong?","answer":"No. For a query returning a large share of the table, a full scan with multiblock reads is cheaper than thousands of index probes. The number that decides is logical reads (Buffers) per row returned: if a full scan reads fewer buffers than the indexed alternative would, the optimizer is right and the rewrite should target returning fewer rows."},{"question":"Why do the E-Rows and A-Rows diverge so much on one line?","answer":"The optimizer estimated from statistics that no longer match the data - skewed columns, recently bulk-loaded data, or a predicate the stats do not describe. Gather stats with a method_opt that keeps histograms on the skewed column, then re-check. Persistent divergence on the same line is the single most common cause of a bad plan."},{"question":"Can I read execution plans without SQL Developer?","answer":"Yes. DBMS_XPLAN output is plain text you can paste into SQLly's free query plan viewer at /tools/query-plan-viewer, and the SQLly desktop app opens plan output in its built-in plan viewer next to the query editor."}],"plan_group":null,"related_slugs":[]},"source_url":"https://sqlly.app/sql-performance/oracle","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/parallel-query-plans","corpus":"sql-performance","engine":null,"language":"en","title":"Parallel plans that do not run in parallel","description":"A plan that launched fewer workers than planned, put most rows on one thread, or was forced to run serial. How to read each case and what to change.","body":{"slug":"parallel-query-plans","engines":["PostgreSQL","SQL Server"],"symptoms":["Slow query","High CPU"],"h1":"Parallel plans that do not run in parallel","lede":"A parallel plan only helps when the work is really spread over several workers. How to spot a PostgreSQL plan that launched fewer workers than it planned, a SQL Server plan where one thread did nearly everything, and a plan that was not allowed to go parallel at all.","symptom_html":"<p>A parallel plan splits a scan, join or aggregate over several workers. Three things go wrong with it, and all three are written in the plan. PostgreSQL can plan for workers it does not get at run time. SQL Server can hand almost every row to one thread while the others sit idle. And SQL Server can be stopped from building a parallel plan at all, in which case the plan records why.</p>\n<p>The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> flags each of these. The examples use a shop schema with 400,000 orders in three statuses: 384,000 shipped, 12,000 cancelled and 4,000 pending.</p>","diagnosis_html":"<h3>PostgreSQL: workers planned and workers launched</h3>\n<p>Every <code>Gather</code> or <code>Gather Merge</code> node in an <code>EXPLAIN ANALYZE</code> plan prints two numbers. <code>Workers Planned</code> is what the planner costed the plan for. <code>Workers Launched</code> is what the node got when it ran.</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT status, count(*) FROM orders GROUP BY status;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Finalize GroupAggregate  (cost=7982.08..7982.96 rows=3 width=16) (actual rows=3.00 loops=1)\n  Group Key: status\n  -&gt;  Gather Merge  (cost=7982.08..7982.89 rows=7 width=16) (actual rows=9.00 loops=1)\n        Workers Planned: 2\n        Workers Launched: 2\n        -&gt;  Sort  (cost=6982.06..6982.06 rows=3 width=16) (actual rows=3.00 loops=3)\n              Sort Key: status\n              Sort Method: quicksort  Memory: 25kB\n              Worker 0:  Sort Method: quicksort  Memory: 25kB\n              Worker 1:  Sort Method: quicksort  Memory: 25kB\n              -&gt;  Partial HashAggregate  (cost=6982.00..6982.03 rows=3 width=16) (actual rows=3.00 loops=3)\n                    Group Key: status\n                    Batches: 1  Memory Usage: 32kB\n                    Worker 0:  Batches: 1  Memory Usage: 32kB\n                    Worker 1:  Batches: 1  Memory Usage: 32kB\n                    -&gt;  Parallel Seq Scan on orders  (cost=0.00..6148.67 rows=166667 width=8) (actual rows=133333.33 loops=3)</code></pre>\n<p>The row counts under a <code>Gather</code> are averages per process. <code>rows=133333.33 loops=3</code> on the scan means three processes (two workers and the leader) read 400,000 rows between them.</p>\n<p>Workers come out of a pool shared by the whole server. When the pool is empty the query still runs, with fewer workers or with none. You can see what that looks like by emptying the pool for your own session:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SET max_parallel_workers = 0;\n\nEXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT status, count(*) FROM orders GROUP BY status;\n\nRESET max_parallel_workers;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Finalize GroupAggregate  (cost=7982.08..7982.96 rows=3 width=16) (actual rows=3.00 loops=1)\n  Group Key: status\n  -&gt;  Gather Merge  (cost=7982.08..7982.89 rows=7 width=16) (actual rows=3.00 loops=1)\n        Workers Planned: 2\n        Workers Launched: 0\n        -&gt;  Sort  (cost=6982.06..6982.06 rows=3 width=16) (actual rows=3.00 loops=1)\n              Sort Key: status\n              Sort Method: quicksort  Memory: 25kB\n              -&gt;  Partial HashAggregate  (cost=6982.00..6982.03 rows=3 width=16) (actual rows=3.00 loops=1)\n                    Group Key: status\n                    Batches: 1  Memory Usage: 32kB\n                    -&gt;  Parallel Seq Scan on orders  (cost=0.00..6148.67 rows=166667 width=8) (actual rows=400000.00 loops=1)</code></pre>\n<p>The plan shape is the same, but <code>Workers Launched: 0</code> and <code>loops=1</code> on the scan say the leader read all 400,000 rows alone. The plan was costed for three processes and ran on one, so it is slower than its estimate, and sometimes slower than the serial plan the planner would have picked had it known.</p>\n<h3>PostgreSQL: the three limits</h3>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SELECT name, setting, context\nFROM pg_settings\nWHERE name IN ('max_worker_processes', 'max_parallel_workers',\n               'max_parallel_workers_per_gather')\nORDER BY name;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>             name               | setting |  context\nmax_parallel_workers            | 8       | user\nmax_parallel_workers_per_gather | 2       | user\nmax_worker_processes            | 8       | postmaster</code></pre>\n<p><a href=\"/sql-configuration/postgresql/max-parallel-workers-per-gather\">max_parallel_workers_per_gather</a> caps the workers one <code>Gather</code> node may plan for. <a href=\"/sql-configuration/postgresql/max-parallel-workers\">max_parallel_workers</a> caps the workers running for parallel queries across all sessions. <a href=\"/sql-configuration/postgresql/max-worker-processes\">max_worker_processes</a> is the size of the pool that parallel workers share with other background workers; its <code>postmaster</code> context means a change needs a restart.</p>\n<p>To see how many workers are busy right now:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SELECT count(*) AS parallel_workers_running\nFROM pg_stat_activity\nWHERE backend_type = 'parallel worker';</code></pre>\n<h3>SQL Server: was the plan allowed to go parallel?</h3>\n<p>The root of the plan XML carries a <code>DegreeOfParallelism</code> attribute. When something stopped the optimizer from considering a parallel plan, the same element has a <code>NonParallelPlanReason</code>. Capture the actual plan with <code>SET STATISTICS XML ON</code>, or with Include Actual Execution Plan in your client, and look at the <code>QueryPlan</code> element:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS XML ON;\nGO\nSELECT MAX(rn)\nFROM (SELECT ROW_NUMBER() OVER (PARTITION BY Status ORDER BY OrderDate) AS rn\n      FROM dbo.Orders) AS x\nOPTION (MAXDOP 1);\nGO\nSET STATISTICS XML OFF;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>NonParallelPlanReason=\"MaxDOPSetToOne\"</code></pre>\n<p><code>MaxDOPSetToOne</code> is the reason for a <code>MAXDOP 1</code> hint, for a database scoped <code>MAXDOP</code> of 1 and for a server-wide <a href=\"/sql-configuration/sql-server/max-degree-of-parallelism\">max degree of parallelism</a> of 1. Two other reasons come from the query itself. An insert into a table variable is always serial:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS XML ON;\nGO\nDECLARE @t TABLE (OrderId int, rn bigint);\n\nINSERT INTO @t\nSELECT OrderId, ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY OrderDate)\nFROM dbo.Orders;\nGO\nSET STATISTICS XML OFF;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>NonParallelPlanReason=\"TableVariableTransactionsDoNotSupportParallelNestedTransaction\"</code></pre>\n<p>A scalar user-defined function that is not inlined gives <code>TSQLUserDefinedFunctionsNotParallelizable</code>; the <a href=\"/sql-performance/scalar-udf\">scalar function guide</a> covers that one.</p>\n<p>A plan with <code>DegreeOfParallelism=\"1\"</code> and no reason is different. Nothing blocked it. The optimizer costed the serial plan below <a href=\"/sql-configuration/sql-server/cost-threshold-for-parallelism\">cost threshold for parallelism</a>, or found the serial plan cheaper.</p>\n<h3>SQL Server: rows per thread</h3>\n<p>In an actual plan each operator lists the rows every thread handled, in <code>RunTimeCountersPerThread</code> elements. A row-mode window function partitioned on a column with three values shows what skew looks like. The hint keeps this example in row mode:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS XML ON;\nGO\nSELECT MAX(rn)\nFROM (SELECT ROW_NUMBER() OVER (PARTITION BY Status ORDER BY OrderDate) AS rn\n      FROM dbo.Orders) AS x\nOPTION (USE HINT('DISALLOW_BATCH_MODE'));\nGO\nSET STATISTICS XML OFF;</code></pre>\n<p>The plan ran with <code>DegreeOfParallelism=\"7\"</code>. These are the counters of its <code>Sort</code>, cut down to the thread number and the row count:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>&lt;RunTimeCountersPerThread Thread=\"7\" ActualRows=\"4000\" /&gt;\n&lt;RunTimeCountersPerThread Thread=\"6\" ActualRows=\"12000\" /&gt;\n&lt;RunTimeCountersPerThread Thread=\"5\" ActualRows=\"0\" /&gt;\n&lt;RunTimeCountersPerThread Thread=\"4\" ActualRows=\"384000\" /&gt;\n&lt;RunTimeCountersPerThread Thread=\"3\" ActualRows=\"0\" /&gt;\n&lt;RunTimeCountersPerThread Thread=\"2\" ActualRows=\"0\" /&gt;\n&lt;RunTimeCountersPerThread Thread=\"1\" ActualRows=\"0\" /&gt;\n&lt;RunTimeCountersPerThread Thread=\"0\" ActualRows=\"0\" /&gt;</code></pre>\n<p>Thread 0 is the coordinator and never carries rows in a parallel zone. Of the seven workers, four got nothing and one sorted 384,000 of the 400,000 rows. The <code>Repartition Streams</code> operator below the sort sends all rows with the same <code>Status</code> to the same thread, and there are only three statuses, so no more than three threads can ever have work. Which thread number gets which status changes from run to run.</p>\n<p>The scan at the bottom of the same plan is spread evenly, at 10,000 to 80,000 rows a thread. Skew starts at the exchange that repartitions on a column with few values, or with one value that dominates.</p>","fix_html":"<h3>PostgreSQL: give the query its workers</h3>\n<p>If plans often launch fewer workers than planned, the pool is too small for the load. Raise the pool and the parallel share of it together. <code>max_parallel_workers</code> above <code>max_worker_processes</code> has no effect, and <code>max_worker_processes</code> only changes at a restart:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>ALTER SYSTEM SET max_worker_processes = 16;\nALTER SYSTEM SET max_parallel_workers = 16;</code></pre>\n<p>If one kind of query should use more workers than the default two, raise the per-node limit for that session. On this table that alone changes nothing, because the planner picks the worker count from the size of the table and settles on two. A storage parameter on the table overrides that choice:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SET max_parallel_workers_per_gather = 4;\nALTER TABLE orders SET (parallel_workers = 4);\n\nEXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF, COSTS OFF)\nSELECT status, count(*) FROM orders GROUP BY status;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Workers Planned: 4\nWorkers Launched: 4\n            -&gt;  Parallel Seq Scan on orders (actual rows=80000.00 loops=5)</code></pre>\n<p>Both limits apply. With <code>max_parallel_workers_per_gather</code> left at 2, the same table setting still plans two workers. To put both back:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>RESET max_parallel_workers_per_gather;\nALTER TABLE orders RESET (parallel_workers);</code></pre>\n<h3>PostgreSQL: a function that blocks parallelism</h3>\n<p>When a query you expected to be parallel has no <code>Gather</code> node at all, check the functions it calls. A user-defined function is <code>PARALLEL UNSAFE</code> unless it says otherwise, and one unsafe function makes the whole query serial:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE FUNCTION net_total(t numeric) RETURNS numeric\nLANGUAGE plpgsql AS 'BEGIN RETURN t / 1.2; END';\n\nEXPLAIN (COSTS OFF)\nSELECT status, sum(net_total(total)) FROM orders GROUP BY status;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>HashAggregate\n  Group Key: status\n  -&gt;  Seq Scan on orders</code></pre>\n<p>If the function reads no temporary tables, writes nothing and changes no session state, mark it safe:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>ALTER FUNCTION net_total(numeric) PARALLEL SAFE;\n\nEXPLAIN (COSTS OFF)\nSELECT status, sum(net_total(total)) FROM orders GROUP BY status;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Finalize GroupAggregate\n  Group Key: status\n  -&gt;  Gather Merge\n        Workers Planned: 2\n        -&gt;  Sort\n              Sort Key: status\n              -&gt;  Partial HashAggregate\n                    Group Key: status\n                    -&gt;  Parallel Seq Scan on orders</code></pre>\n<h3>SQL Server: remove what forces the serial plan</h3>\n<p>For <code>MaxDOPSetToOne</code>, find where the 1 comes from: a hint in the query text, the database, or the server.</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT name, value FROM sys.database_scoped_configurations WHERE name = 'MAXDOP';\n\nSELECT name, value_in_use FROM sys.configurations\nWHERE name IN ('max degree of parallelism', 'cost threshold for parallelism');</code></pre>\n<p>For the table variable reason, load a temporary table instead. The insert stays serial but the query that feeds it runs in parallel:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE TABLE #t (OrderId int, rn bigint);\nGO\nSET STATISTICS XML ON;\nGO\nINSERT INTO #t\nSELECT OrderId, ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY OrderDate)\nFROM dbo.Orders\nOPTION (USE HINT('DISALLOW_BATCH_MODE'));\nGO\nSET STATISTICS XML OFF;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>DegreeOfParallelism=\"7\"</code></pre>\n<h3>SQL Server: deal with the skew</h3>\n<p>First measure whether the parallel plan is buying anything. Run the skewed query and its serial twin with <code>SET STATISTICS TIME ON</code> and compare:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS TIME ON;\nGO\nSELECT MAX(rn)\nFROM (SELECT ROW_NUMBER() OVER (PARTITION BY Status ORDER BY OrderDate) AS rn\n      FROM dbo.Orders) AS x\nOPTION (USE HINT('DISALLOW_BATCH_MODE'));\nGO\nSELECT MAX(rn)\nFROM (SELECT ROW_NUMBER() OVER (PARTITION BY Status ORDER BY OrderDate) AS rn\n      FROM dbo.Orders) AS x\nOPTION (USE HINT('DISALLOW_BATCH_MODE'), MAXDOP 1);\nGO\nSET STATISTICS TIME OFF;</code></pre>\n<p>On the test server both finished in about 300 ms, and the parallel one used more CPU to get there. When one thread does all the work, seven threads are no faster than one, and a <code>MAXDOP 1</code> hint on that statement gives the other queries their cores back.</p>\n<p>The better fix removes the repartitioning. Here that is batch mode: without the row-mode hint, SQL Server 2025 runs the same query with a <code>Window Aggregate</code> operator that needs no exchange on <code>Status</code>, and it finished in about 70 ms on the same server.</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS TIME ON;\nGO\nSELECT MAX(rn)\nFROM (SELECT ROW_NUMBER() OVER (PARTITION BY Status ORDER BY OrderDate) AS rn\n      FROM dbo.Orders) AS x;\nGO\nSET STATISTICS TIME OFF;</code></pre>\n<p>Where the skew comes from a join or a <code>GROUP BY</code>, look at the column the exchange partitions on. A column with few values, or one value that covers most rows, will always skew.</p>\n<h3>When to leave it alone</h3>\n<p>A serial plan is the right plan for a query that finishes in milliseconds; starting workers costs more than it saves. A PostgreSQL query that now and then launches one worker fewer on a busy server is working as designed. And skew on an operator that handles a few thousand rows costs nothing you can measure. Act when the query is slow and the plan shows it was costed for parallel work it did not get.</p>","checklist_html":["PostgreSQL: compare Workers Planned with Workers Launched on every Gather node.","Check max_parallel_workers, max_parallel_workers_per_gather and max_worker_processes in pg_settings.","No Gather node at all: look for a user-defined function that is not marked PARALLEL SAFE.","SQL Server: read DegreeOfParallelism and NonParallelPlanReason on the QueryPlan element.","For MaxDOPSetToOne, check the query hint, the database scoped MAXDOP and the server setting.","Compare ActualRows per thread on the operators above a Repartition Streams exchange.","Time the query against a MAXDOP 1 run before deciding the parallel plan is worth keeping."],"faqs":[{"question":"What does Workers Launched: 0 mean in PostgreSQL?","answer":"The plan was built for parallel workers but none were available when it ran, so the leader process did all the work alone. The limit that ran out is max_parallel_workers or max_worker_processes, both shared by every session on the server."},{"question":"Why are the row counts under a Gather node smaller than the table?","answer":"EXPLAIN ANALYZE shows rows per loop, and under a Gather node each participating process counts as one loop. Multiply rows by loops to get the total. A scan that shows rows=133333.33 loops=3 read 400,000 rows."},{"question":"What is NonParallelPlanReason in a SQL Server plan?","answer":"It is an attribute on the QueryPlan element of the plan XML that says why the optimizer could not consider a parallel plan. MaxDOPSetToOne means a hint or a setting limits the query to one thread. Other values point at something in the query, such as a scalar user-defined function or an insert into a table variable."},{"question":"Does a serial plan always have a NonParallelPlanReason?","answer":"No. The attribute appears only when something prevented a parallel plan. A cheap query whose estimated cost is below cost threshold for parallelism gets a serial plan with no reason attached."},{"question":"How do I see how many rows each thread processed in SQL Server?","answer":"Capture the actual execution plan. In the XML each operator has one RunTimeCountersPerThread element per thread with an ActualRows attribute. Graphical plan tools show the same numbers in the operator's properties."}],"plan_group":"Parallelism, functions and compile time","related_slugs":["scalar-udf","sort-and-hash-spills","high-cpu"]},"source_url":"https://sqlly.app/sql-performance/parallel-query-plans","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/parameter-sniffing","corpus":"sql-performance","engine":null,"language":"en","title":"Parameter sniffing and cached plans","description":"A plan built for one parameter value is reused for another that needs a different plan. How to prove it from the plan and the fixes, in order of cost.","body":{"slug":"parameter-sniffing","engines":["SQL Server","PostgreSQL"],"symptoms":["Sudden slowdown","Slow query"],"h1":"Parameter sniffing and cached plans","lede":"The same procedure is fast for one customer and slow for another, or fast until a restart and slow after. The plan was built for the first value it saw and reused for all the rest. How to prove it and what to change.","symptom_html":"<p>A parameterized query is compiled once and its plan is cached. To build that plan the optimizer looks at the parameter values of the call that triggered compilation, which is called sniffing. Most of the time that is what you want. It goes wrong when the data is skewed: a plan built for a customer with 20 orders is reused for a customer with 40,000, or the other way round.</p>\n<p>The signs are a query that is fast or slow depending on who ran it first, performance that changes after a restart, a failover or a statistics update, and a query that is slow from the application but fast when you paste it into a query window with the values typed in. The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> reports a SQL Server plan whose compiled and runtime parameter values differ and whose row estimates are far off. The examples use a shop schema with 400,000 orders: customer 1 has 40,000 of them, every other customer about 20.</p>","diagnosis_html":"<h3>SQL Server: reproduce it with two calls</h3>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);\nGO\nCREATE OR ALTER PROCEDURE dbo.GetCustomerOrders @CustomerId int\nAS\nSELECT OrderId, Total, Reference FROM dbo.Orders WHERE CustomerId = @CustomerId;\nGO\nSET NOCOUNT ON;\nSET STATISTICS IO ON;\nGO\nEXEC dbo.GetCustomerOrders @CustomerId = 4242;\nGO\nEXEC dbo.GetCustomerOrders @CustomerId = 1;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 63, physical reads 0\nTable 'Orders'. Scan count 1, logical reads 120073, physical reads 0</code></pre>\n<p>The first call compiled a plan for a customer with 20 orders: an index seek and a <a href=\"/sql-performance/key-lookup\">key lookup</a> per row. The second call reused it for 40,000 rows and paid for 40,000 lookups. Now clear the plan and call in the other order:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>EXEC sp_recompile 'dbo.GetCustomerOrders';\nGO\nEXEC dbo.GetCustomerOrders @CustomerId = 1;\nGO\nEXEC dbo.GetCustomerOrders @CustomerId = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 2579, physical reads 0\nTable 'Orders'. Scan count 1, logical reads 2579, physical reads 0</code></pre>\n<p>This time the plan was built for customer 1 and scans the table, which is right for 40,000 rows and wasteful for 20. Neither plan is wrong; each is wrong for the other value.</p>\n<h3>SQL Server: compiled value against runtime value</h3>\n<p>An actual execution plan records both values. In Management Studio they are in the properties of the root operator under <code>Parameter List</code>. In the XML:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>EXEC sp_recompile 'dbo.GetCustomerOrders';\nGO\nEXEC dbo.GetCustomerOrders @CustomerId = 4242;\nGO\nSET STATISTICS XML ON;\nGO\nEXEC dbo.GetCustomerOrders @CustomerId = 1;\nGO\nSET STATISTICS XML OFF;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>&lt;ColumnReference Column=\"@CustomerId\" ParameterDataType=\"int\" ParameterCompiledValue=\"(4242)\" ParameterRuntimeValue=\"(1)\" /&gt;</code></pre>\n<p>A compiled value that differs from the runtime value, on a plan whose estimated rows are far from the actual rows, is the proof. A plan taken from the cache has only the compiled value. That is still useful: it tells you which call the plan was built for.</p>\n<h3>PostgreSQL: custom and generic plans</h3>\n<p>PostgreSQL works the other way round. For a prepared statement it plans each of the first five executions with the actual values (a custom plan). After that it may switch to a generic plan, built without looking at any value, if the generic plan does not look more expensive than the custom ones did on average. A generic plan shows the parameter as <code>$1</code> where a custom plan shows the value:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\n\nPREPARE customer_orders (int) AS\nSELECT order_id, total, reference FROM orders WHERE customer_id = $1;\n\nEXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nEXECUTE customer_orders (1);\n\nSET plan_cache_mode = force_generic_plan;\n\nEXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nEXECUTE customer_orders (1);</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Bitmap Heap Scan on orders  (cost=458.91..5435.25 rows=39547 width=17) (actual rows=40000.00 loops=1)\n  Recheck Cond: (customer_id = 1)\n  -&gt;  Bitmap Index Scan on orders_customer_idx  (cost=0.00..449.02 rows=39547 width=0) (actual rows=40000.00 loops=1)\n        Index Cond: (customer_id = 1)\nBitmap Heap Scan on orders  (cost=4.60..91.95 rows=23 width=17) (actual rows=40000.00 loops=1)\n  Recheck Cond: (customer_id = $1)\n  -&gt;  Bitmap Index Scan on orders_customer_idx  (cost=0.00..4.60 rows=23 width=0) (actual rows=40000.00 loops=1)\n        Index Cond: (customer_id = $1)</code></pre>\n<p>The generic plan expects the average customer, 23 rows, and gets the largest one. The scan happens to have the same shape here; in a larger query that estimate decides the join method and join order above it. To see which kind your sessions are running, <code>pg_prepared_statements</code> counts both for the current session:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SELECT name, generic_plans, custom_plans FROM pg_prepared_statements;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>     name       | generic_plans | custom_plans\ncustomer_orders |             1 |            1</code></pre>","fix_html":"<h3>Give the query a plan that suits every value</h3>\n<p>Sniffing only hurts when different values need different plans. Often an index change removes the difference. Here the two plans differ because the index does not cover the query; once it does, a seek is the best plan for any customer and there is nothing left to get wrong:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId)\n    INCLUDE (Total, Reference) WITH (DROP_EXISTING = ON);\nGO\nEXEC dbo.GetCustomerOrders @CustomerId = 4242;\nGO\nEXEC dbo.GetCustomerOrders @CustomerId = 1;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 3, physical reads 0\nTable 'Orders'. Scan count 1, logical reads 170, physical reads 0</code></pre>\n<h3>SQL Server: recompile the statement</h3>\n<p><code>OPTION (RECOMPILE)</code> builds a fresh plan for the values of every call. It always gets the right plan and always pays for a compilation, so it suits queries that run a few times a minute, not thousands of times a second.</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>DROP INDEX IX_Orders_CustomerId ON dbo.Orders;\nCREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);\nGO\nCREATE OR ALTER PROCEDURE dbo.GetCustomerOrders @CustomerId int\nAS\nSELECT OrderId, Total, Reference FROM dbo.Orders WHERE CustomerId = @CustomerId\nOPTION (RECOMPILE);\nGO\nEXEC dbo.GetCustomerOrders @CustomerId = 4242;\nGO\nEXEC dbo.GetCustomerOrders @CustomerId = 1;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 63, physical reads 0\nTable 'Orders'. Scan count 1, logical reads 2579, physical reads 0</code></pre>\n<h3>SQL Server: plan for the average value</h3>\n<p><code>OPTIMIZE FOR UNKNOWN</code> tells the optimizer to ignore the sniffed value and use the average number of rows per value. Every call gets the same plan whatever ran first. That makes performance predictable; it does not make the plan good for the unusual value.</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE OR ALTER PROCEDURE dbo.GetCustomerOrders @CustomerId int\nAS\nSELECT OrderId, Total, Reference FROM dbo.Orders WHERE CustomerId = @CustomerId\nOPTION (OPTIMIZE FOR UNKNOWN);\nGO\nEXEC dbo.GetCustomerOrders @CustomerId = 1;\nGO\nEXEC dbo.GetCustomerOrders @CustomerId = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 1, logical reads 120073, physical reads 0\nTable 'Orders'. Scan count 1, logical reads 63, physical reads 0</code></pre>\n<p>The database-wide version of this hint is the <a href=\"/sql-configuration/sql-server/parameter-sniffing\">PARAMETER_SNIFFING</a> database scoped configuration. When one specific plan is known to be acceptable for all values, <a href=\"/sql-configuration/sql-server/query-store\">Query Store</a> can force it without a code change, and the <a href=\"/sql-snippets/plan-regressions-query-store\">plan regressions snippet</a> finds queries whose plan changed for the worse.</p>\n<h3>PostgreSQL: force custom plans</h3>\n<p>When a generic plan is the problem, tell PostgreSQL to plan with the actual values every time:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SET plan_cache_mode = force_custom_plan;\n\nEXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nEXECUTE customer_orders (1);\n\nDEALLOCATE customer_orders;\nRESET plan_cache_mode;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Bitmap Heap Scan on orders  (cost=458.91..5435.25 rows=39547 width=17) (actual rows=40000.00 loops=1)\n  Recheck Cond: (customer_id = 1)\n  -&gt;  Bitmap Index Scan on orders_customer_idx  (cost=0.00..449.02 rows=39547 width=0) (actual rows=40000.00 loops=1)\n        Index Cond: (customer_id = 1)</code></pre>\n<p>The setting can be applied to a session, a role or a database, so it can be limited to the application that needs it. The cost is planning time on every execution.</p>\n<h3>When to leave it alone</h3>\n<p>Sniffing is the normal, useful behaviour, and a compiled value that differs from the runtime value is not a problem by itself: that is true of nearly every cached plan. Leave it when the row estimates are close to the actual counts, or when both values would get the same plan. Do not turn sniffing off for a whole database because one procedure misbehaves.</p>","checklist_html":["Compare the compiled and runtime parameter values in the actual plan (SQL Server).","Check that estimated and actual rows differ widely on the operators that use the parameter.","Run the query with a common value and with an unusual one, after clearing its plan, to see both plans.","First try an index that makes one plan good for every value.","Otherwise recompile per call for infrequent queries, or plan for the average for frequent ones.","In PostgreSQL, check pg_prepared_statements and try plan_cache_mode = force_custom_plan."],"faqs":[{"question":"What is parameter sniffing?","answer":"When SQL Server compiles a parameterized query or procedure, it uses the parameter values of that first call to estimate row counts, then caches the plan and reuses it for later calls. The plan is tuned for the first values. It becomes a problem only when other values need a different plan."},{"question":"Why is the query fast in Management Studio and slow from the application?","answer":"Usually because the two are not sharing a plan. Session settings such as ARITHABORT differ between Management Studio and most client libraries, so each gets its own cached plan, compiled for different parameter values. Typing literal values instead of parameters also produces a different plan."},{"question":"Does restarting or updating statistics fix parameter sniffing?","answer":"It clears the cached plan, so the next call compiles a new one for whatever values it happens to carry. That may fix the symptom or bring it back. It explains why the problem seems to come and go."},{"question":"Is OPTION (RECOMPILE) safe to use?","answer":"It is safe and gives each call a plan built for its own values. The cost is a compilation on every execution, which adds CPU time. Use it on queries that run occasionally and take long enough that compile time does not matter."},{"question":"Does PostgreSQL have parameter sniffing?","answer":"Not in the same form. PostgreSQL plans a prepared statement with the real values for its first five executions and then may switch to a generic plan that ignores them. The equivalent problem is a generic plan that is poor for unusual values, and plan_cache_mode controls it."}],"plan_group":"Row estimates and statistics","related_slugs":["row-estimate-mismatch","sudden-slowdown","key-lookup"]},"source_url":"https://sqlly.app/sql-performance/parameter-sniffing","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/partition-pruning","corpus":"sql-performance","engine":null,"language":"en","title":"Partition pruning in the plan","description":"A query on a partitioned table that reads every partition gets none of the benefit. How to see which partitions the plan touches and why pruning fails.","body":{"slug":"partition-pruning","engines":["PostgreSQL","MySQL","SQL Server"],"symptoms":["Slow query","Bad index usage"],"h1":"Partition pruning in the plan","lede":"A partitioned table is only fast when the plan can skip partitions. How PostgreSQL, MySQL and SQL Server show which partitions a query reads, the filters that prevent pruning, and how to write the query so the partition key does its job.","symptom_html":"<p>Partitioning splits a table into pieces by the value of a partition key, usually a date. A query that filters on the key only has to read the pieces that can contain matching rows; the engine skips the rest, which is called partition pruning or partition elimination. A query that does not filter on the key, or filters on it in a way the engine cannot use, reads every partition. It is then slower than the same query on an unpartitioned table, because it repeats its work once per partition.</p>\n<p>The plan says exactly which partitions were read. The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> flags a filtered query that touches all of them. The examples partition 400,000 orders by year: 2023, 2024 and 2025.</p>","diagnosis_html":"<h3>PostgreSQL: the partitions are listed in the plan</h3>\n<p>Each partition is a table of its own, and the plan names the ones it scans.</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE TABLE orders_part (LIKE orders) PARTITION BY RANGE (order_date);\nCREATE TABLE orders_part_2023 PARTITION OF orders_part FOR VALUES FROM ('2023-01-01') TO ('2024-01-01');\nCREATE TABLE orders_part_2024 PARTITION OF orders_part FOR VALUES FROM ('2024-01-01') TO ('2025-01-01');\nCREATE TABLE orders_part_2025 PARTITION OF orders_part FOR VALUES FROM ('2025-01-01') TO ('2026-01-01');\nINSERT INTO orders_part SELECT * FROM orders;\nANALYZE orders_part;\n\nEXPLAIN (COSTS OFF)\nSELECT count(*) FROM orders_part\nWHERE order_date &gt;= '2024-03-01' AND order_date &lt; '2024-04-01';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Finalize Aggregate\n  -&gt;  Gather\n        Workers Planned: 1\n        -&gt;  Partial Aggregate\n              -&gt;  Parallel Seq Scan on orders_part_2024 orders_part\n                    Filter: ((order_date &gt;= '2024-03-01 00:00:00'::timestamp without time zone) AND (order_date &lt; '2024-04-01 00:00:00'::timestamp without time zone))</code></pre>\n<p>Only <code>orders_part_2024</code> appears. A filter on another column cannot prune, and neither can a function around the key:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (COSTS OFF)\nSELECT count(*) FROM orders_part WHERE customer_id = 4242;\n\nEXPLAIN (COSTS OFF)\nSELECT count(*) FROM orders_part WHERE date_trunc('month', order_date) = '2024-03-01';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Finalize Aggregate\n  -&gt;  Gather\n        Workers Planned: 2\n        -&gt;  Partial Aggregate\n              -&gt;  Parallel Append\n                    -&gt;  Parallel Seq Scan on orders_part_2024 orders_part_2\n                          Filter: (customer_id = 4242)\n                    -&gt;  Parallel Seq Scan on orders_part_2023 orders_part_1\n                          Filter: (customer_id = 4242)\n                    -&gt;  Parallel Seq Scan on orders_part_2025 orders_part_3\n                          Filter: (customer_id = 4242)\nFinalize Aggregate\n  -&gt;  Gather\n        Workers Planned: 2\n        -&gt;  Partial Aggregate\n              -&gt;  Parallel Append\n                    -&gt;  Parallel Seq Scan on orders_part_2024 orders_part_2\n                          Filter: (date_trunc('month'::text, order_date) = '2024-03-01 00:00:00'::timestamp without time zone)\n                    -&gt;  Parallel Seq Scan on orders_part_2023 orders_part_1\n                          Filter: (date_trunc('month'::text, order_date) = '2024-03-01 00:00:00'::timestamp without time zone)\n                    -&gt;  Parallel Seq Scan on orders_part_2025 orders_part_3\n                          Filter: (date_trunc('month'::text, order_date) = '2024-03-01 00:00:00'::timestamp without time zone)</code></pre>\n<p>When the key is compared with a parameter, pruning happens when the query starts, not when it is planned. The plan then reports how many partitions it dropped as <code>Subplans Removed</code>:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SET plan_cache_mode = force_generic_plan;\nPREPARE recent_orders (timestamp) AS\nSELECT count(*) FROM orders_part WHERE order_date &gt;= $1;\n\nEXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nEXECUTE recent_orders ('2025-02-01');\n\nDEALLOCATE recent_orders;\nRESET plan_cache_mode;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Finalize Aggregate (actual rows=1.00 loops=1)\n  -&gt;  Gather (actual rows=3.00 loops=1)\n        Workers Planned: 2\n        Workers Launched: 2\n        -&gt;  Partial Aggregate (actual rows=1.00 loops=3)\n              -&gt;  Parallel Append (actual rows=11413.67 loops=3)\n                    Subplans Removed: 2\n                    -&gt;  Parallel Seq Scan on orders_part_2025 orders_part_1 (actual rows=11413.67 loops=3)\n                          Filter: (order_date &gt;= $1)\n                          Rows Removed by Filter: 4960</code></pre>\n<h3>MySQL: the partitions column</h3>\n<p><code>EXPLAIN</code> has a <code>partitions</code> column that lists what the query will read.</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>CREATE TABLE orders_part (\n    order_id int NOT NULL,\n    customer_id int NOT NULL,\n    status varchar(20) NOT NULL,\n    order_date datetime NOT NULL,\n    total decimal(10,2) NOT NULL,\n    reference varchar(20) NOT NULL,\n    PRIMARY KEY (order_id, order_date)\n)\nPARTITION BY RANGE COLUMNS (order_date) (\n    PARTITION p2023 VALUES LESS THAN ('2024-01-01'),\n    PARTITION p2024 VALUES LESS THAN ('2025-01-01'),\n    PARTITION p2025 VALUES LESS THAN (MAXVALUE)\n);\nINSERT INTO orders_part SELECT * FROM orders;\nANALYZE TABLE orders_part;\n\nEXPLAIN SELECT count(*) FROM orders_part\nWHERE order_date &gt;= '2024-03-01' AND order_date &lt; '2024-04-01'\\G</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>partitions: p2024\n      type: index\n      rows: 170976</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN SELECT count(*) FROM orders_part WHERE customer_id = 4242\\G\n\nEXPLAIN SELECT count(*) FROM orders_part WHERE MONTH(order_date) = 3\\G</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>partitions: p2023,p2024,p2025\n      type: ALL\n      rows: 395072\npartitions: p2023,p2024,p2025\n      type: index\n      rows: 395072</code></pre>\n<p>Every unique key on a partitioned MySQL table, the primary key included, must contain the partition column. That is why the primary key here is <code>(order_id, order_date)</code>.</p>\n<h3>SQL Server: Actual Partition Count</h3>\n<p>SQL Server keeps one plan operator for the whole table and records the partitions it touched in the operator's properties: <code>Actual Partition Count</code> and <code>Actual Partitions Accessed</code> in Management Studio, <code>RunTimePartitionSummary</code> in the plan XML.</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE PARTITION FUNCTION pfOrderYear (datetime2(0))\n    AS RANGE RIGHT FOR VALUES ('2024-01-01', '2025-01-01');\nCREATE PARTITION SCHEME psOrderYear\n    AS PARTITION pfOrderYear ALL TO ([PRIMARY]);\nCREATE TABLE dbo.OrdersPart (\n    OrderId int NOT NULL,\n    CustomerId int NOT NULL,\n    Status varchar(20) NOT NULL,\n    OrderDate datetime2(0) NOT NULL,\n    Total decimal(10,2) NOT NULL,\n    Reference varchar(20) NOT NULL,\n    CONSTRAINT PK_OrdersPart PRIMARY KEY CLUSTERED (OrderId, OrderDate)\n) ON psOrderYear (OrderDate);\nINSERT INTO dbo.OrdersPart SELECT * FROM dbo.Orders;\nGO\nSET STATISTICS XML ON;\nGO\nDECLARE @from datetime2(0) = '2024-03-01', @to datetime2(0) = '2024-04-01';\nSELECT COUNT(*) FROM dbo.OrdersPart\nWHERE OrderDate &gt;= @from AND OrderDate &lt; @to;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>&lt;PartitionsAccessed PartitionCount=\"1\"&gt;&lt;PartitionRange Start=\"2\" End=\"2\" /&gt;&lt;/PartitionsAccessed&gt;</code></pre>\n<p>One partition of three. A filter on another column reads them all:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT COUNT(*) FROM dbo.OrdersPart WHERE CustomerId = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>&lt;PartitionsAccessed PartitionCount=\"3\"&gt;&lt;PartitionRange Start=\"1\" End=\"3\" /&gt;&lt;/PartitionsAccessed&gt;</code></pre>\n<p>The type of the value matters here. The same date range written as plain string literals reads all three partitions on this table:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT COUNT(*) FROM dbo.OrdersPart\nWHERE OrderDate &gt;= '2024-03-01' AND OrderDate &lt; '2024-04-01';</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>&lt;PartitionsAccessed PartitionCount=\"3\"&gt;&lt;PartitionRange Start=\"1\" End=\"3\" /&gt;&lt;/PartitionsAccessed&gt;</code></pre>\n<p>SQL Server turned the literals into <code>varchar</code> parameters and converted them to <code>datetime2(7)</code>, which is not the type of the partition column, and elimination was lost. Variables or parameters declared as <code>datetime2(0)</code>, or a <code>CAST</code> of each literal to that type, bring it back. This is an <a href=\"/sql-performance/implicit-conversion\">implicit conversion</a> problem showing up as a partitioning problem.</p>\n<p>To see how the rows are spread over the partitions:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS XML OFF;\n\nSELECT partition_number, rows\nFROM sys.partitions\nWHERE object_id = OBJECT_ID('dbo.OrdersPart') AND index_id = 1\nORDER BY partition_number;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>1 175199\n2 175680\n3 49121</code></pre>","fix_html":"<h3>Filter on the partition key</h3>\n<p>If the query knows the period it wants, say so in the <code>WHERE</code> clause, even when another condition already identifies the rows. Adding the date range to the customer filter cuts the work to one partition:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (COSTS OFF)\nSELECT count(*) FROM orders_part\nWHERE customer_id = 4242\n  AND order_date &gt;= '2024-01-01' AND order_date &lt; '2025-01-01';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Finalize Aggregate\n  -&gt;  Gather\n        Workers Planned: 1\n        -&gt;  Partial Aggregate\n              -&gt;  Parallel Seq Scan on orders_part_2024 orders_part\n                    Filter: ((order_date &gt;= '2024-01-01 00:00:00'::timestamp without time zone) AND (order_date &lt; '2025-01-01 00:00:00'::timestamp without time zone) AND (customer_id = 4242))</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN SELECT count(*) FROM orders_part\nWHERE customer_id = 4242\n  AND order_date &gt;= '2024-01-01' AND order_date &lt; '2025-01-01'\\G</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>partitions: p2024\n      type: ALL\n      rows: 170976</code></pre>\n<h3>Compare the bare key with a range</h3>\n<p>A function around the key hides it from the pruning logic in the same way it hides a column from an index. Write the condition as a range on the column itself: <code>order_date &gt;= '2024-03-01' AND order_date &lt; '2024-04-01'</code>, not <code>date_trunc('month', order_date) = '2024-03-01'</code>. The rewrite is the same one that fixes <a href=\"/sql-performance/non-sargable-predicates\">non-sargable predicates</a>.</p>\n<h3>Index the partitions for queries that cannot use the key</h3>\n<p>Some queries have no period to filter on. They will visit every partition, and the goal becomes making each visit cheap. An index created on the partitioned table is built on every partition:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_part_customer_idx ON orders_part (customer_id);\n\nEXPLAIN (COSTS OFF)\nSELECT count(*) FROM orders_part WHERE customer_id = 4242;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Aggregate\n  -&gt;  Append\n        -&gt;  Bitmap Heap Scan on orders_part_2023 orders_part_1\n              Recheck Cond: (customer_id = 4242)\n              -&gt;  Bitmap Index Scan on orders_part_2023_customer_id_idx\n                    Index Cond: (customer_id = 4242)\n        -&gt;  Bitmap Heap Scan on orders_part_2024 orders_part_2\n              Recheck Cond: (customer_id = 4242)\n              -&gt;  Bitmap Index Scan on orders_part_2024_customer_id_idx\n                    Index Cond: (customer_id = 4242)\n        -&gt;  Bitmap Heap Scan on orders_part_2025 orders_part_3\n              Recheck Cond: (customer_id = 4242)\n              -&gt;  Bitmap Index Scan on orders_part_2025_customer_id_idx\n                    Index Cond: (customer_id = 4242)</code></pre>\n<p>Three index probes are cheap. Three hundred are not, which is a reason to keep the number of partitions modest when many queries cannot prune.</p>\n<h3>PostgreSQL: check that pruning is enabled</h3>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SHOW enable_partition_pruning;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>enable_partition_pruning\non</code></pre>\n<p>It is <code>on</code> by default. If it reports <code>off</code>, someone changed it, and no query on the server prunes.</p>\n<h3>When to leave it alone</h3>\n<p>A query that needs rows from every period is supposed to read every partition: a count of all orders per customer has nothing to prune. Leave it alone too when the partitions are few and each one is read through an index. Pruning matters for the queries the partitioning was designed for, the ones that ask for a slice of time.</p>","checklist_html":["Find which partitions the plan reads: the scan nodes (PostgreSQL), the partitions column (MySQL), Actual Partition Count (SQL Server).","Check that the WHERE clause filters on the partition key at all.","Remove any function, cast or calculation around the key.","Add the period to the query when the application knows it.","For queries that cannot filter on the key, index each partition on the column they do filter on.","Re-capture the plan and confirm fewer partitions are read."],"faqs":[{"question":"What is partition pruning?","answer":"It is the step where the engine works out, from the WHERE clause and the partition boundaries, which partitions cannot contain matching rows and leaves them out of the plan. SQL Server calls the same thing partition elimination."},{"question":"Why does my query scan all partitions?","answer":"Either it does not filter on the partition key, or the filter wraps the key in a function or cast so the engine cannot compare it with the partition boundaries. A filter on any other column, even an indexed one, does not prune."},{"question":"What does Subplans Removed mean in PostgreSQL?","answer":"It is the number of partitions PostgreSQL dropped when the query started running, after it learned the values of parameters. Partitions pruned at planning time do not appear in the plan at all; those pruned at execution start are counted in Subplans Removed."},{"question":"Does partitioning make queries faster?","answer":"Only the queries that prune. A query that reads one partition of twenty touches a twentieth of the data. A query that cannot prune pays a small extra cost for every partition. Partitioning mainly helps with maintenance, such as dropping old data, and with time-sliced queries."},{"question":"Does a join on the partition key prune?","answer":"It can at run time. PostgreSQL prunes partitions inside a nested loop when the key is compared with a value from the outer row; those scans are shown as never executed. A direct filter with a constant or parameter is the more reliable way to get pruning."}],"plan_group":"Indexes and access paths","related_slugs":["non-sargable-predicates","full-table-scan","implicit-conversion"]},"source_url":"https://sqlly.app/sql-performance/partition-pruning","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/postgresql","corpus":"sql-performance","engine":null,"language":"en","title":"PostgreSQL query performance troubleshooting","description":"Diagnose slow PostgreSQL queries with pg_stat_statements, EXPLAIN ANALYZE and BUFFERS, then fix seq scans, stale stats and bloat.","body":{"slug":"postgresql","engines":["PostgreSQL"],"symptoms":["Slow query","Bad index usage","Memory pressure"],"h1":"PostgreSQL query performance troubleshooting","lede":"A method for slow PostgreSQL queries: rank statements with pg_stat_statements, read EXPLAIN (ANALYZE, BUFFERS), then fix the seq scans, bad estimates and bloat it shows.","symptom_html":"<p>A query on PostgreSQL takes seconds where it should take milliseconds, or the database quietly eats CPU all day. Everything below ships with PostgreSQL; one piece, pg_stat_statements, has to be switched on first, and that takes a server restart.</p>","diagnosis_html":"<h3>Rank the statements with pg_stat_statements</h3>\n<p>The module is in the standard contrib package but is not loaded by default. Add it to <code>shared_preload_libraries</code>, restart, then create the extension in the database you connect to. Until the library is preloaded, querying the view fails with <code>pg_stat_statements must be loaded via \"shared_preload_libraries\"</code>. Managed services (RDS, Cloud SQL, Azure) usually preload it already, so only the CREATE EXTENSION step is left:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>-- postgresql.conf, then restart:\n-- shared_preload_libraries = 'pg_stat_statements'\nCREATE EXTENSION IF NOT EXISTS pg_stat_statements;\n\nSELECT calls,\nround(mean_exec_time::numeric, 1) AS mean_ms,\nround(total_exec_time::numeric) AS total_ms,\nleft(query, 80) AS query\nFROM pg_stat_statements\nORDER BY total_exec_time DESC\nLIMIT 10;</code></pre>\n<p>Total time finds the queries that hurt the server; mean time finds the ones that hurt your users. A query called 40,000 times a day at 3 ms each costs more than the nightly report that takes a minute. Constants are replaced with <code>$1</code>, <code>$2</code> in the <code>query</code> text, so every run of the same statement shape lands in one row. The column names above are PostgreSQL 13 and later; older versions call them <code>total_time</code> and <code>mean_time</code>. Seeing other users' query text needs superuser or the <code>pg_read_all_stats</code> role.</p>\n<h3>Read the plan with real timings and buffers</h3>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, BUFFERS)\nSELECT o.id, o.total, c.name\nFROM orders AS o\nJOIN customers AS c ON c.id = o.customer_id\nWHERE o.status = 'pending'\nAND o.created_at &gt;= now() - interval '7 days';</code></pre>\n<p>Three things to check, in order: where the plan scans (<code>Seq Scan</code> on a big table is the usual suspect), where the estimate diverges from the actual rows (a bad row estimate sends the planner down the wrong path), and where the buffers come from (<code>hit=</code> was found in shared_buffers; <code>read=</code> had to be fetched from the operating system, either its page cache or the disk - a hot query should be nearly all hits). <code>EXPLAIN ANALYZE</code> really runs the statement, so wrap writes in <code>BEGIN; ... ROLLBACK;</code>. From PostgreSQL 18, BUFFERS is included automatically with ANALYZE. Paste the plan into the <a href=\"/tools/query-plan-viewer\">query plan viewer</a> for a readable rendering, and format the SQL with the <a href=\"/tools/sql-formatter\">SQL formatter</a> if the query itself is a wall of text.</p>\n<h3>Check what the tables are doing</h3>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SELECT relname, seq_scan, seq_tup_read,\nidx_scan, n_live_tup, n_dead_tup, last_autovacuum\nFROM pg_stat_user_tables\nORDER BY seq_tup_read DESC\nLIMIT 10;</code></pre>\n<p>A large <code>seq_tup_read</code> with a small <code>idx_scan</code> means queries are crawling the heap because no index matches them. A growing <code>n_dead_tup</code> with a stale <code>last_autovacuum</code> means bloat, which makes every scan slower for everyone.</p>\n<h3>Look for lock waits when it is intermittent</h3>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SELECT pid, wait_event_type, wait_event, state, left(query, 60) AS query\nFROM pg_stat_activity\nWHERE wait_event_type = 'Lock';</code></pre>\n<p>A query that is usually fast but sometimes hangs is almost always waiting on a lock, not on the planner - see the <a href=\"/sql-performance/blocking-deadlocks\">blocking and deadlocks guide</a> for who is holding it.</p>","fix_html":"<p><strong>Index what the plan scans.</strong> For the pending-orders example, one index carries the whole plan: equality predicate first, range last, and every other column the query reads from <code>orders</code> as INCLUDEs (PostgreSQL 11+) so the plan can become an Index Only Scan:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX CONCURRENTLY idx_orders_status_created\nON orders (status, created_at DESC)\nINCLUDE (id, customer_id, total);</code></pre>\n<p><code>CONCURRENTLY</code> matters on any table people write to - a plain CREATE INDEX blocks inserts, updates and deletes until it finishes. It cannot run inside a transaction block, and if it fails it leaves an INVALID index behind that you must drop. Leave out any column from the INCLUDE list and the plan falls back to an Index Scan that visits the heap for each row. An Index Only Scan also depends on the visibility map, so a table that autovacuum has not processed recently shows a high <code>Heap Fetches</code> count in the plan.</p>\n<p><strong>Give the planner honest statistics.</strong> The default <code>default_statistics_target</code> of 100 is fine for most columns; for a skewed column whose rare values matter, raise it for that column only:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>ALTER TABLE orders ALTER COLUMN status SET STATISTICS 500;\nANALYZE orders;</code></pre>\n<p><strong>Reclaim the bloat.</strong> If <code>n_dead_tup</code> dwarfs <code>n_live_tup</code>, tune autovacuum on that table (<code>ALTER TABLE orders SET (autovacuum_vacuum_scale_factor = 0.01);</code>, down from the default 0.2) rather than scheduling manual VACUUMs. Then check that nothing is holding back cleanup: an old <code>xact_start</code> in <code>pg_stat_activity</code>, a session <code>idle in transaction</code>, or a stale replication slot keeps every dead row since then from being removed.</p>\n<p><strong>Size memory for the working set.</strong> Persistent <code>read=</code> buffers on hot tables mean the cache is too small - the <a href=\"/sql-performance/memory-pressure\">memory pressure guide</a> walks through <code>shared_buffers</code>, <code>work_mem</code> and what to measure before changing them.</p>","checklist_html":["Preload pg_stat_statements (restart), CREATE EXTENSION, and let it accumulate at least a day of history.","List the top 10 by total_exec_time and by mean_exec_time; they are usually different lists.","EXPLAIN (ANALYZE, BUFFERS) the top offender and note every Seq Scan on a table over ~10k rows.","Check estimated vs actual rows on each node; diverging estimates mean statistics work first.","Create the covering index CONCURRENTLY for the dominant scan pattern.","Re-run the EXPLAIN and confirm the Seq Scan became an Index Scan or Index Only Scan and the buffer counts dropped.","Review pg_stat_user_tables weekly for dead-tuple growth and stale autovacuum timestamps."],"faqs":[{"question":"Why does EXPLAIN ANALYZE take longer than the query itself?","answer":"ANALYZE really executes the statement, and the instrumentation costs extra per row - on big sorts and hashes the overhead is noticeable. Wrap the statement in BEGIN/ROLLBACK when profiling writes so the changes are undone, or run it on a replica."},{"question":"The planner uses a Seq Scan even though an index exists. Why?","answer":"Usually one of three things: the predicate does not match the index's leading column, the planner believes the scan will return most of the table (check the row estimates), or the column types do not match so an implicit cast blocks the index. EXPLAIN's filter condition tells you which - the index-not-used guide walks through each."},{"question":"How do I find queries that got slower over time?","answer":"pg_stat_statements is cumulative: it survives a clean restart (pg_stat_statements.save is on by default) and only resets when you call pg_stat_statements_reset() or the server crashes. It has no history of its own, so snapshot it into a table on a schedule and diff the snapshots, or set log_min_duration_statement and feed the log to pgBadger for trending. A query whose mean time crept up while its calls stayed flat is a plan or bloat problem, not a traffic problem."},{"question":"Is VACUUM FULL a normal maintenance task?","answer":"No - it takes an ACCESS EXCLUSIVE lock that blocks even reads, and rewrites the whole table, needing free disk space for the new copy. Plain VACUUM, which autovacuum runs, makes dead space reusable without that lock. Treat VACUUM FULL as a one-off repair for extreme bloat, and fix the underlying problem (long transactions, undersized autovacuum) instead of scheduling it."},{"question":"Can I read execution plans without a database connection?","answer":"Yes. Paste the EXPLAIN output into SQLly's free query plan viewer at /tools/query-plan-viewer; it renders the tree in your browser. The SQLly desktop app has the same plan viewer built in next to the query editor."}],"plan_group":null,"related_slugs":[]},"source_url":"https://sqlly.app/sql-performance/postgresql","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/postgresql-jit-and-planning-time","corpus":"sql-performance","engine":null,"language":"en","title":"JIT overhead and planning time","description":"When a short PostgreSQL query spends its time compiling or planning instead of running. How to read the JIT block and Planning Time, and what to change.","body":{"slug":"postgresql-jit-and-planning-time","engines":["PostgreSQL"],"symptoms":["Slow query","High CPU"],"h1":"JIT overhead and planning time","lede":"Some PostgreSQL queries are slow before they read a single row. How to tell from EXPLAIN ANALYZE that JIT compilation or planning took longer than the work itself, and how to bring each one down.","symptom_html":"<p>Two lines at the bottom of an <code>EXPLAIN ANALYZE</code> plan describe time spent outside the plan's operators. <code>Planning Time</code> is how long the planner took to choose the plan. The <code>JIT</code> block, when there is one, is how long PostgreSQL spent compiling parts of the query to machine code before and while running it. For a long report query both are noise. For a query that should take a millisecond they can be most of the bill.</p>\n<p>The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> flags a plan where JIT took a large share of the run time, and one where planning took longer than execution. The examples use a shop schema with 20,000 customers, 400,000 orders and 800,000 order items.</p>","diagnosis_html":"<h3>The JIT block</h3>\n<p>PostgreSQL turns JIT on for a query when the plan's estimated cost passes a threshold. The sample tables are too small to pass the defaults, so this session lowers the thresholds to show what the block looks like:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SET jit_above_cost = 0;\nSET jit_inline_above_cost = 0;\nSET jit_optimize_above_cost = 0;\n\nEXPLAIN (ANALYZE, BUFFERS OFF)\nSELECT count(*) FROM customers WHERE country = 'DE';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>  -&gt;  Seq Scan on customers  (cost=0.00..417.00 rows=4000 width=0) (actual time=40.401..40.921 rows=4000.00 loops=1)\nPlanning Time: 0.138 ms\nJIT:\n  Functions: 4\n  Options: Inlining true, Optimization true, Expressions true, Deforming true\n  Timing: Generation 0.101 ms (Deform 0.027 ms), Inlining 33.114 ms, Optimization 3.335 ms, Emission 3.927 ms, Total 40.477 ms\nExecution Time: 51.044 ms</code></pre>\n<p>Compare <code>Total</code> on the <code>Timing</code> line with <code>Execution Time</code>. Here compilation is most of the run. The time shows up inside the plan too: the scan's <code>actual time</code> starts late, because the first row had to wait for the compiler. Without JIT the same query is far quicker:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SET jit = off;\n\nEXPLAIN (ANALYZE, BUFFERS OFF)\nSELECT count(*) FROM customers WHERE country = 'DE';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>  -&gt;  Seq Scan on customers  (cost=0.00..417.00 rows=4000 width=0) (actual time=0.004..0.585 rows=4000.00 loops=1)\nPlanning Time: 0.052 ms\nExecution Time: 0.689 ms</code></pre>\n<h3>Why JIT was chosen</h3>\n<p>The decision uses the estimated cost of the whole plan and nothing else. Put the session back to its defaults and look at them:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>RESET jit;\nRESET jit_above_cost;\nRESET jit_inline_above_cost;\nRESET jit_optimize_above_cost;\n\nSELECT name, setting\nFROM pg_settings\nWHERE name IN ('jit', 'jit_above_cost', 'jit_inline_above_cost', 'jit_optimize_above_cost')\nORDER BY name;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>         name           | setting\njit                     | on\njit_above_cost          | 100000\njit_inline_above_cost   | 500000\njit_optimize_above_cost | 500000</code></pre>\n<p>A plan costed above <code>jit_above_cost</code> is compiled. Above the other two thresholds it is also inlined and optimized, which are the expensive steps in the <code>Timing</code> line. So JIT on a query that turns out to be short usually means the cost estimate was too high, and that leads back to a <a href=\"/sql-performance/row-estimate-mismatch\">row estimate that is far off</a>. Check the estimates in the plan before touching the settings.</p>\n<h3>Planning time</h3>\n<p>A point lookup across several joined tables runs in microseconds, but the planner still has to consider the join orders:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, BUFFERS OFF)\nSELECT c.email, o1.total, i1.product_id, i2.product_id,\n       o2.order_id, o3.order_id, c2.email, i3.quantity\nFROM orders o1\nJOIN customers c ON c.customer_id = o1.customer_id\nJOIN order_items i1 ON i1.order_id = o1.order_id AND i1.line_no = 1\nJOIN order_items i2 ON i2.order_id = o1.order_id AND i2.line_no = 2\nJOIN orders o2 ON o2.order_id = o1.order_id + 1\nJOIN orders o3 ON o3.order_id = o1.order_id + 2\nJOIN customers c2 ON c2.customer_id = o2.customer_id\nJOIN order_items i3 ON i3.order_id = o3.order_id AND i3.line_no = 1\nWHERE o1.order_id = 42;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Planning Time: 1.055 ms\nExecution Time: 0.118 ms</code></pre>\n<p>Planning took many times longer than running. The first plan in a new session is slower still, because the session has to load the table and index definitions into its cache; run the statement twice before you read the number.</p>\n<p>Planning time grows with the number of joined tables, the number of indexes on them and the number of partitions the planner has to look at. A query over a table with hundreds of partitions that does not filter on the partition key plans every partition; <a href=\"/sql-performance/partition-pruning\">partition pruning</a> covers that case.</p>","fix_html":"<h3>JIT: fix the estimate, then the threshold</h3>\n<p>If the plan's row estimates are wrong, fix those first; a correct, lower cost keeps the query under the threshold with no setting changed. If the estimates are right and short queries still get compiled, raise the threshold for the session, role or database that runs them:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SET jit_above_cost = 500000;</code></pre>\n<p>Or turn JIT off where the workload is all short queries. It can be set per session, as above, or for one role:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE ROLE app_web;\nALTER ROLE app_web SET jit = off;</code></pre>\n<p>The <a href=\"/sql-configuration/postgresql/jit\">jit setting page</a> covers the server-wide switch.</p>\n<h3>Planning: prepare the statement</h3>\n<p>A prepared statement can keep its plan. Once PostgreSQL settles on a generic plan for it, later executions skip planning. Setting <code>plan_cache_mode</code> makes that happen from the first execution:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>PREPARE order_detail(int) AS\nSELECT c.email, o1.total, i1.product_id, i2.product_id,\n       o2.order_id, o3.order_id, c2.email, i3.quantity\nFROM orders o1\nJOIN customers c ON c.customer_id = o1.customer_id\nJOIN order_items i1 ON i1.order_id = o1.order_id AND i1.line_no = 1\nJOIN order_items i2 ON i2.order_id = o1.order_id AND i2.line_no = 2\nJOIN orders o2 ON o2.order_id = o1.order_id + 1\nJOIN orders o3 ON o3.order_id = o1.order_id + 2\nJOIN customers c2 ON c2.customer_id = o2.customer_id\nJOIN order_items i3 ON i3.order_id = o3.order_id AND i3.line_no = 1\nWHERE o1.order_id = $1;\n\nSET plan_cache_mode = force_generic_plan;\nEXPLAIN (ANALYZE, BUFFERS OFF) EXECUTE order_detail(42);\nEXPLAIN (ANALYZE, BUFFERS OFF) EXECUTE order_detail(42);</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Planning Time: 0.707 ms\nExecution Time: 0.030 ms\nPlanning Time: 0.002 ms\nExecution Time: 0.019 ms</code></pre>\n<p>The first execution plans the statement; the second reuses the plan. Most drivers prepare statements for you when you use bind parameters. A generic plan is built without knowing the parameter values, which is fine for a key lookup like this one and risky where different values need different plans; <a href=\"/sql-performance/parameter-sniffing\">parameter-sensitive plans</a> explains the trade.</p>\n<h3>Planning: give the planner less to consider</h3>\n<p>For a query whose join order you already know, <code>join_collapse_limit = 1</code> makes the planner join the tables in the order they are written:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SET join_collapse_limit = 1;\n\nEXPLAIN (ANALYZE, BUFFERS OFF)\nSELECT c.email, o1.total, i1.product_id, i2.product_id,\n       o2.order_id, o3.order_id, c2.email, i3.quantity\nFROM orders o1\nJOIN customers c ON c.customer_id = o1.customer_id\nJOIN order_items i1 ON i1.order_id = o1.order_id AND i1.line_no = 1\nJOIN order_items i2 ON i2.order_id = o1.order_id AND i2.line_no = 2\nJOIN orders o2 ON o2.order_id = o1.order_id + 1\nJOIN orders o3 ON o3.order_id = o1.order_id + 2\nJOIN customers c2 ON c2.customer_id = o2.customer_id\nJOIN order_items i3 ON i3.order_id = o3.order_id AND i3.line_no = 1\nWHERE o1.order_id = 42;\n\nRESET join_collapse_limit;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Planning Time: 0.152 ms\nExecution Time: 0.028 ms</code></pre>\n<p>Set it for that one statement or transaction only. With the limit at 1 a badly ordered query gets exactly the plan it was written as.</p>\n<h3>When to leave it alone</h3>\n<p>A JIT block on a query that runs for seconds is doing its job, and its cost is a rounding error. Planning that takes longer than execution is normal for any fast query; a millisecond of planning in front of a tenth of a millisecond of work is still a millisecond. It is worth fixing when that statement runs thousands of times a second, or when planning takes tens of milliseconds.</p>","checklist_html":["Run EXPLAIN ANALYZE twice and read Planning Time, Execution Time and the JIT block of the second run.","JIT: compare the Total on the Timing line with Execution Time.","Check the plan's row estimates before changing a JIT threshold; an inflated cost is the usual trigger.","Raise jit_above_cost, or set jit = off for the role that runs short queries.","Planning: count the joined tables, their indexes and the partitions the query touches.","Use prepared statements so repeated executions reuse the plan."],"faqs":[{"question":"What is the JIT section in a PostgreSQL EXPLAIN ANALYZE plan?","answer":"It reports just-in-time compilation: PostgreSQL compiled expressions and row decoding for this query to machine code. The Timing line gives the time spent generating, inlining, optimizing and emitting that code. That time is part of the query's run time."},{"question":"Should I turn JIT off in PostgreSQL?","answer":"For a workload of short queries, turning it off or raising jit_above_cost is reasonable, because compilation can cost more than it saves. For long analytic queries JIT usually pays for itself. You can set it per role or per session and keep both."},{"question":"Why is Planning Time higher than Execution Time?","answer":"The planner's work depends on how many tables, indexes and partitions it has to consider, not on how many rows the query returns. A lookup that joins eight tables by primary key runs in microseconds but still has many join orders to cost. The first statement in a new session also pays for loading catalog information."},{"question":"Do prepared statements reduce planning time in PostgreSQL?","answer":"Yes, once the statement uses a generic plan. PostgreSQL plans a prepared statement with the actual parameter values for its first executions, then switches to a cached generic plan if that is not costlier. plan_cache_mode = force_generic_plan makes it use the cached plan right away."},{"question":"Does JIT time count toward Execution Time?","answer":"Yes. Compilation happens during execution, so the Execution Time at the bottom of the plan includes it. In a parallel plan the Timing line adds up the compilation done by the leader and every worker, so its total can be larger than the elapsed time."}],"plan_group":"Parallelism, functions and compile time","related_slugs":["row-estimate-mismatch","partition-pruning","parameter-sniffing"]},"source_url":"https://sqlly.app/sql-performance/postgresql-jit-and-planning-time","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/reading-execution-plans","corpus":"sql-performance","engine":null,"language":"en","title":"How to read an execution plan","description":"How to capture an execution plan with run-time numbers on each engine, the order to read it in, and which numbers tell you where the query went wrong.","body":{"slug":"reading-execution-plans","engines":["SQL Server","PostgreSQL","MySQL","SQLite","Oracle"],"symptoms":["Slow query"],"h1":"How to read an execution plan","lede":"An execution plan is the list of steps the database took to answer a query. How to get one that includes what really happened, how to read it, and which numbers to look at first.","symptom_html":"<p>Every engine can show how it ran a query: which tables it read, in what order, how it joined them and how many rows moved between the steps. There are two kinds of plan. An estimated plan is what the optimizer intends to do, with its guesses for row counts. An actual plan is produced by running the query and adds what happened: real row counts, and on most engines time and pages read per step. Most plan problems are a difference between the two, so get an actual plan whenever the query is safe to run.</p>\n<p>Paste either kind into the <a href=\"/tools/query-plan-viewer\">query plan viewer</a> to see it as a diagram with the costly steps marked. The examples use a shop schema with 20,000 customers, 400,000 orders and 800,000 order items, and the same query on every engine: orders that are still pending, counted by the customer's country.</p>","diagnosis_html":"<h3>PostgreSQL</h3>\n<p><code>EXPLAIN</code> alone shows the estimated plan. <code>ANALYZE</code> runs the statement and adds the actual numbers; <code>BUFFERS</code> adds pages read per step. For the viewer, <code>FORMAT JSON</code> carries the same information.</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, BUFFERS)\nSELECT c.country, count(*)\nFROM customers c\nJOIN orders o ON o.customer_id = c.customer_id\nWHERE o.status = 'pending'\nGROUP BY c.country;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Finalize GroupAggregate  (cost=8194.41..8195.92 rows=5 width=11) (actual time=8.715..10.571 rows=1.00 loops=1)\n  Group Key: c.country\n  Buffers: shared hit=4997\n  -&gt;  Gather Merge  (cost=8194.41..8195.81 rows=12 width=11) (actual time=8.711..10.568 rows=3.00 loops=1)\n        Workers Planned: 2\n        Workers Launched: 2\n        Buffers: shared hit=4997\n        -&gt;  Sort  (cost=7194.39..7194.40 rows=5 width=11) (actual time=7.460..7.461 rows=1.00 loops=3)\n              Sort Key: c.country\n              Sort Method: quicksort  Memory: 25kB\n              Buffers: shared hit=4997\n              Worker 0:  Sort Method: quicksort  Memory: 25kB\n              Worker 1:  Sort Method: quicksort  Memory: 25kB\n              -&gt;  Partial HashAggregate  (cost=7194.28..7194.33 rows=5 width=11) (actual time=7.449..7.450 rows=1.00 loops=3)\n                    Group Key: c.country\n                    Batches: 1  Memory Usage: 32kB\n                    Buffers: shared hit=4983\n                    Worker 0:  Batches: 1  Memory Usage: 32kB\n                    Worker 1:  Batches: 1  Memory Usage: 32kB\n                    -&gt;  Hash Join  (cost=617.00..7186.45 rows=1567 width=3) (actual time=2.154..7.338 rows=1333.33 loops=3)\n                          Hash Cond: (o.customer_id = c.customer_id)\n                          Buffers: shared hit=4983\n                          -&gt;  Parallel Seq Scan on orders o  (cost=0.00..6565.33 rows=1567 width=4) (actual time=0.006..5.088 rows=1333.33 loops=3)\n                                Filter: ((status)::text = 'pending'::text)\n                                Rows Removed by Filter: 132000\n                                Buffers: shared hit=4482\n                          -&gt;  Hash  (cost=367.00..367.00 rows=20000 width=7) (actual time=2.071..2.071 rows=20000.00 loops=3)\n                                Buckets: 32768  Batches: 1  Memory Usage: 1038kB\n                                Buffers: shared hit=501\n                                -&gt;  Seq Scan on customers c  (cost=0.00..367.00 rows=20000 width=7) (actual time=0.006..0.814 rows=20000.00 loops=3)\n                                      Buffers: shared hit=501\nPlanning Time: 0.285 ms\nExecution Time: 10.659 ms</code></pre>\n<p>Each line has two brackets. The first is the estimate: <code>cost</code> in the planner's own units and <code>rows</code>. The second is what happened: <code>actual time</code> in milliseconds, <code>rows</code> and <code>loops</code>. Time and rows are averages per loop, so multiply by <code>loops</code> to get the total. The scan of <code>orders</code> above ran in three processes and each found a third of the pending orders.</p>\n<h3>MySQL and MariaDB</h3>\n<p>MySQL 8.0.18 and later run the statement with <code>EXPLAIN ANALYZE</code> and print a tree with estimates and actual numbers side by side:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN ANALYZE\nSELECT c.country, count(*)\nFROM customers c\nJOIN orders o ON o.customer_id = c.customer_id\nWHERE o.status = 'pending'\nGROUP BY c.country;</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Table scan on &lt;temporary&gt;  (actual time=44.5..44.5 rows=1 loops=1)\n    -&gt; Aggregate using temporary table  (actual time=44.5..44.5 rows=1 loops=1)\n        -&gt; Nested loop inner join  (cost=54270 rows=39933) (actual time=0.0756..44.1 rows=4000 loops=1)\n            -&gt; Filter: (o.`status` = 'pending')  (cost=40294 rows=39933) (actual time=0.07..43.5 rows=4000 loops=1)\n                -&gt; Table scan on o  (cost=40294 rows=399330) (actual time=0.0611..30.8 rows=400000 loops=1)\n            -&gt; Single-row index lookup on c using PRIMARY (customer_id=o.customer_id)  (cost=0.25 rows=1) (actual time=56.8e-6..71.6e-6 rows=1 loops=4000)</code></pre>\n<p>As in PostgreSQL, <code>actual time</code> and <code>rows</code> are per loop. The last line ran 4,000 times, once per pending order. Plain <code>EXPLAIN</code> gives the estimated plan as a table, and <code>EXPLAIN FORMAT=JSON</code> gives it with costs.</p>\n<p>MariaDB uses <code>ANALYZE</code> in place of <code>EXPLAIN ANALYZE</code>; the statement is there from MariaDB 10.1 on. <code>ANALYZE FORMAT=JSON</code> prints the detailed form, where the fields that start with <code>r_</code> are the measured ones, next to the estimates without the prefix: <code>r_loops</code> and <code>r_rows</code> per table, with <code>r_filtered</code> beside the estimated <code>filtered</code>.</p>\n<h3>SQL Server</h3>\n<p><code>SET STATISTICS XML ON</code> runs each statement and returns its actual plan as an extra result set holding one XML document. Save that document as a <code>.sqlplan</code> file or paste it into the viewer.</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS XML ON;\nGO\nSELECT c.Country, COUNT(*) AS Orders\nFROM dbo.Customers AS c\nJOIN dbo.Orders AS o ON o.CustomerId = c.CustomerId\nWHERE o.Status = 'pending'\nGROUP BY c.Country;\nGO\nSET STATISTICS XML OFF;</code></pre>\n<p><code>SET SHOWPLAN_XML ON</code> returns the estimated plan in the same format without running the statement. <code>SET SHOWPLAN_TEXT ON</code> does the same as plain text, which is easier to read in a terminal:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET SHOWPLAN_TEXT ON;\nGO\nSELECT c.Country, COUNT(*) AS Orders\nFROM dbo.Customers AS c\nJOIN dbo.Orders AS o ON o.CustomerId = c.CustomerId\nWHERE o.Status = 'pending'\nGROUP BY c.Country;\nGO\nSET SHOWPLAN_TEXT OFF;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>|--Compute Scalar(DEFINE:([Expr1002]=CONVERT_IMPLICIT(int,[Expr1005],0)))\n     |--Hash Match(Aggregate, HASH:([c].[Country]), RESIDUAL:([learnfx].[dbo].[Customers].[Country] as [c].[Country] = [learnfx].[dbo].[Customers].[Country] as [c].[Country]) DEFINE:([Expr1005]=COUNT(*)))\n          |--Merge Join(Inner Join, MERGE:([c].[CustomerId])=([o].[CustomerId]), RESIDUAL:([learnfx].[dbo].[Customers].[CustomerId] as [c].[CustomerId]=[learnfx].[dbo].[Orders].[CustomerId] as [o].[CustomerId]))\n               |--Clustered Index Scan(OBJECT:([learnfx].[dbo].[Customers].[PK__Customer__A4AE64D854FCACE0] AS [c]), ORDERED FORWARD)\n               |--Sort(ORDER BY:([o].[CustomerId] ASC))\n                    |--Clustered Index Scan(OBJECT:([learnfx].[dbo].[Orders].[PK__Orders__C3905BCFF902724C] AS [o]), WHERE:([learnfx].[dbo].[Orders].[Status] as [o].[Status]='pending'))</code></pre>\n<h3>Oracle</h3>\n<p><code>EXPLAIN PLAN</code> gives an estimated plan. For actual numbers, run the statement with the <code>GATHER_PLAN_STATISTICS</code> hint and then ask for the plan of the last statement in the session. In SQL*Plus turn <code>SERVEROUTPUT</code> off first, or the last statement is not the one you ran.</p>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>SET SERVEROUTPUT OFF\n\nSELECT /*+ GATHER_PLAN_STATISTICS */ c.country, count(*)\nFROM customers c\nJOIN orders o ON o.customer_id = c.customer_id\nWHERE o.status = 'pending'\nGROUP BY c.country;\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(FORMAT =&gt; 'ALLSTATS LAST'));</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation           | Name      | Starts | E-Rows | A-Rows |   A-Time   | Buffers |  OMem |  1Mem | Used-Mem |\n|   0 | SELECT STATEMENT    |           |      1 |        |      1 |00:00:00.01 |    2512 |       |       |          |\n|   1 |  HASH GROUP BY      |           |      1 |      5 |      1 |00:00:00.01 |    2512 |  1161K|  1161K|          |\n|*  2 |   HASH JOIN         |           |      1 |   4000 |   4000 |00:00:00.01 |    2512 |  2278K|  2278K|  878K (0)|\n|*  3 |    TABLE ACCESS FULL| ORDERS    |      1 |   4000 |   4000 |00:00:00.01 |    2391 |       |       |          |\n|   4 |    TABLE ACCESS FULL| CUSTOMERS |      1 |  20000 |  20000 |00:00:00.01 |     121 |       |       |          |</code></pre>\n<p><code>E-Rows</code> is the estimate and <code>A-Rows</code> the actual row count. <code>Starts</code> is how many times the step ran, <code>A-Time</code> the time spent in the step and everything under it, and <code>Buffers</code> the blocks read.</p>\n<h3>SQLite</h3>\n<p><code>EXPLAIN QUERY PLAN</code> shows the plan without running the query. It has no row counts or timings; what matters is whether each table is read with <code>SCAN</code> (all of it) or <code>SEARCH</code> (through an index or the primary key).</p>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>EXPLAIN QUERY PLAN\nSELECT c.country, count(*)\nFROM customers c\nJOIN orders o ON o.customer_id = c.customer_id\nWHERE o.status = 'pending'\nGROUP BY c.country;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\" data-role=\"output\"><code>|--SCAN o\n|--SEARCH c USING INTEGER PRIMARY KEY (rowid=?)\n`--USE TEMP B-TREE FOR GROUP BY</code></pre>\n<h3>The order to read it in</h3>\n<p>A plan is a tree. The steps indented furthest run first and feed their rows to the step above them, and the top line produces the result. In the PostgreSQL plan above, the scans of <code>orders</code> and <code>customers</code> are the leaves, the hash join combines them, and the aggregates on top count the joined rows. When two steps sit under a join, the engine decides which side drives the other; <a href=\"/sql-performance/join-algorithms\">join algorithms</a> explains how each kind of join uses its two inputs.</p>\n<p>Times and costs are cumulative: the number on a step includes everything beneath it. To find what a step cost by itself, subtract its children. The <a href=\"/sql-performance/execution-plan-operators\">operator reference</a> lists what each kind of step does.</p>","fix_html":"<h3>Find the step where the time goes</h3>\n<p>With an actual plan, walk down from the top and follow the largest time until a step's own time is much larger than its children's. That step, or the rows it was given, is the problem. The usual findings, each with its own guide:</p>\n<ul>\n    <li>A table read in full to return a few rows: <a href=\"/sql-performance/full-table-scan\">full table scan</a> and <a href=\"/sql-performance/missing-index\">missing index</a>.</li>\n    <li>An index used, then one table fetch per row: <a href=\"/sql-performance/key-lookup\">key lookups</a>.</li>\n    <li>A condition the index cannot use: <a href=\"/sql-performance/non-sargable-predicates\">non-sargable predicates</a> and <a href=\"/sql-performance/implicit-conversion\">implicit conversions</a>.</li>\n    <li>A sort or hash that ran out of memory: <a href=\"/sql-performance/sort-and-hash-spills\">spills to disk</a>.</li>\n    <li>A step that ran thousands of times: <a href=\"/sql-performance/correlated-subquery\">correlated subqueries</a> and <a href=\"/sql-performance/join-algorithms\">nested loops over many rows</a>.</li>\n    <li>A join that returns more rows than either input: <a href=\"/sql-performance/join-row-explosion\">join row explosion</a>.</li>\n</ul>\n<p>Whatever change comes out of those guides, capture the same plan before and after, so the improvement is measured rather than remembered. Make sure both runs see the same data and a warm cache, or the comparison proves nothing. The PostgreSQL capture for this page's pending-orders shape:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN ANALYZE\nSELECT o.order_id, o.total\nFROM orders o\nWHERE o.status = 'pending';</code></pre>\n<h3>Compare estimated rows with actual rows</h3>\n<p>Next to every actual row count is the optimizer's estimate. When they differ by a factor of ten or more, the optimizer chose the rest of the plan for a different amount of data than it got: the wrong join type, the wrong join order, too little memory. Find the lowest step in the tree where the two numbers part ways; the cause is there, and everything above inherits it. <a href=\"/sql-performance/row-estimate-mismatch\">Row estimates that are far off</a> covers the causes and fixes.</p>\n<h3>When to leave it alone</h3>\n<p>A scan is not a fault by itself, and neither is a sort or a hash join. A plan is good when the work it does is in proportion to the rows it returns. If the query is fast enough, runs rarely, and its estimates match what happened, there is nothing to fix.</p>","checklist_html":["Capture an actual plan, not only an estimated one, when the query is safe to run.","Read from the most indented steps up to the top line.","Multiply per-loop rows and time by the loop count.","Follow the largest time down the tree to the step that owns it.","Compare estimated and actual rows at every step; start with the lowest step where they differ.","Open the plan in the plan viewer to see the costly steps marked."],"faqs":[{"question":"What is the difference between an estimated and an actual execution plan?","answer":"An estimated plan is what the optimizer intends to do, with predicted row counts, and is produced without running the query. An actual plan comes from running the query and adds the real row counts, and on most engines the time and pages read per step."},{"question":"Does EXPLAIN ANALYZE run the query?","answer":"Yes. In PostgreSQL and MySQL, EXPLAIN ANALYZE executes the statement and discards the result rows. For an INSERT, UPDATE or DELETE the changes are made, so wrap it in a transaction and roll back if you do not want them kept."},{"question":"In what order do I read an execution plan?","answer":"Start at the most indented steps, which read the tables, and work up to the top line, which returns the result. Each step passes its rows to the step above it."},{"question":"What does cost mean in an execution plan?","answer":"Cost is the optimizer's estimate of work in its own units, used to compare alternative plans for the same query. It is not a time. Use the actual time and row counts to judge how the query ran."},{"question":"How do I get an actual execution plan in SQL Server?","answer":"Run SET STATISTICS XML ON before the statement. SQL Server executes it and returns the plan with run-time counts as an XML document in an extra result set. In Management Studio the Include Actual Execution Plan button does the same."}],"plan_group":"Reading the plan","related_slugs":["execution-plan-operators","row-estimate-mismatch","slow-query"]},"source_url":"https://sqlly.app/sql-performance/reading-execution-plans","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/row-estimate-mismatch","corpus":"sql-performance","engine":null,"language":"en","title":"Estimated rows far from actual rows","description":"The optimizer expected 400 rows and got 4,000. Why row estimates go wrong, how to find the first bad one in a plan, and how statistics fix it.","body":{"slug":"row-estimate-mismatch","engines":["PostgreSQL","SQL Server","MySQL","Oracle"],"symptoms":["Slow query","Sudden slowdown"],"h1":"Estimated rows far from actual rows","lede":"Every plan choice rests on a guess at how many rows each step returns. When the guess is far off, the join method, join order and memory are chosen for the wrong amount of data. How to find the first wrong estimate and what to do about each cause.","symptom_html":"<p>Before it runs a query, the optimizer estimates how many rows each step will return, using statistics it keeps about the data. It picks the join method, the join order, the index and the memory for sorts and hashes from those numbers. A plan with actual row counts shows both the guess and the truth, side by side. When they differ by a factor of ten or more, everything above that step was chosen for the wrong amount of data.</p>\n<p>The wrong estimate is rarely the slow step. It is the reason the slow step was chosen. The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> marks the operators where estimate and actual disagree. Start from the one deepest in the plan, since errors carry upwards. The examples use a shop schema with 400,000 orders, where one customer owns 40,000 of them and every <code>pending</code> order belongs to that customer.</p>","diagnosis_html":"<h3>Compare estimated and actual rows</h3>\n<p>PostgreSQL prints both on each line of <code>EXPLAIN ANALYZE</code>: the first <code>rows=</code> is the estimate, the second is what happened.</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT * FROM orders WHERE customer_id = 1 AND status = 'pending';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>-&gt;  Parallel Seq Scan on orders  (cost=0.00..6982.00 rows=164 width=37) (actual rows=1333.33 loops=3)\n      Filter: ((customer_id = 1) AND ((status)::text = 'pending'::text))\n      Rows Removed by Filter: 132000</code></pre>\n<p>In a parallel plan the numbers are per worker, shown by <code>loops</code>; multiply to compare. MySQL shows the same pair in <code>EXPLAIN ANALYZE</code>:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN ANALYZE SELECT * FROM orders WHERE status = 'pending';</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Filter: (orders.`status` = 'pending')  (cost=40225 rows=39864) (actual time=0.0628..53.3 rows=4000 loops=1)\n    -&gt; Table scan on orders  (cost=40225 rows=398641) (actual time=0.0516..40.3 rows=400000 loops=1)</code></pre>\n<p>Oracle reports them as <code>E-Rows</code> and <code>A-Rows</code> when the statement runs with the <code>GATHER_PLAN_STATISTICS</code> hint:</p>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>SELECT /*+ GATHER_PLAN_STATISTICS */ COUNT(*)\nFROM orders WHERE customer_id = 1 AND status = 'pending';\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(format =&gt; 'ALLSTATS LAST'));</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation          | Name   | Starts | E-Rows | A-Rows |   A-Time   | Buffers |\n|   0 | SELECT STATEMENT   |        |      1 |        |      1 |00:00:00.01 |    2391 |\n|   1 |  SORT AGGREGATE    |        |      1 |      1 |      1 |00:00:00.01 |    2391 |\n|*  2 |   TABLE ACCESS FULL| ORDERS |      1 |    394 |   4000 |00:00:00.01 |    2391 |</code></pre>\n<p>In SQL Server, an actual execution plan carries <code>Estimated Number of Rows</code> and <code>Actual Number of Rows</code> on every operator.</p>\n<h3>Check whether the statistics are stale</h3>\n<p>Statistics describe the table as it was when they were last gathered. Rows added since then are invisible to the optimizer. Here 50,000 newer orders are loaded and queried before the statistics catch up:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE TABLE orders_copy AS SELECT * FROM orders;\nANALYZE orders_copy;\n\nINSERT INTO orders_copy\nSELECT order_id + 400000, customer_id, status, order_date + interval '3 years', total, reference\nFROM orders WHERE order_id &lt;= 50000;\n\nEXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT * FROM orders_copy WHERE order_date &gt;= '2026-01-01';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>-&gt;  Parallel Seq Scan on orders_copy  (cost=0.00..6153.29 rows=19 width=37) (actual rows=16666.67 loops=3)\n      Filter: (order_date &gt;= '2026-01-01 00:00:00'::timestamp without time zone)\n      Rows Removed by Filter: 133333</code></pre>\n<p>The newest rows are the usual victims: a query for \"today\" or \"this month\" asks about values past the end of what the statistics have seen. Each engine records when statistics were last gathered:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SELECT relname, n_live_tup, n_mod_since_analyze, last_analyze, last_autoanalyze\nFROM pg_stat_user_tables\nWHERE relname = 'orders_copy';</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT s.name, sp.last_updated, sp.rows, sp.modification_counter\nFROM sys.stats AS s\nCROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) AS sp\nWHERE s.object_id = OBJECT_ID('dbo.Orders');</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>SELECT table_name, n_rows, last_update\nFROM mysql.innodb_table_stats\nWHERE database_name = DATABASE();</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>SELECT table_name, num_rows, stale_stats, last_analyzed\nFROM user_tab_statistics\nWHERE table_name = 'ORDERS';</code></pre>\n<h3>Look for filters the statistics cannot describe</h3>\n<p>Fresh statistics still give wrong answers for some predicates:</p>\n<ul>\n<li><strong>Columns that depend on each other.</strong> The optimizer multiplies the selectivity of each condition as if they were independent. In the first example every pending order belongs to customer 1, so the true count is ten times the product.</li>\n<li><strong>Expressions.</strong> For a calculation on a column, the optimizer has no histogram and falls back to a fixed guess.</li>\n<li><strong>Skewed joins.</strong> A filter on one table that selects a row with far more matches than average in the other.</li>\n</ul>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT * FROM orders WHERE total * 1.2 &gt; 100;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Seq Scan on orders  (cost=0.00..10482.00 rows=133333 width=37) (actual rows=337547.00 loops=1)\n  Filter: ((total * 1.2) &gt; '100'::numeric)\n  Rows Removed by Filter: 62453</code></pre>\n<p>The estimate of 133,333 is exactly one third of the table: the fixed guess PostgreSQL uses for an inequality it knows nothing about.</p>\n<h3>Table variables</h3>\n<p>A SQL Server table variable has no column statistics. Since SQL Server 2019 the optimizer knows how many rows the variable holds when the statement that reads it is first compiled, but it still has to guess how many rows match a filter on it:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS XML ON;\nGO\nDECLARE @recent TABLE (OrderId int PRIMARY KEY, CustomerId int);\nINSERT INTO @recent SELECT OrderId, CustomerId FROM dbo.Orders WHERE OrderId &lt;= 50000;\n\nSELECT COUNT(*) FROM @recent AS r WHERE r.CustomerId = 1;</code></pre>\n<p>On our test server the scan of <code>@recent</code> was estimated at 224 rows and returned 5,000. The same data in a temporary table gets real statistics:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE TABLE #recent (OrderId int PRIMARY KEY, CustomerId int);\nINSERT INTO #recent SELECT OrderId, CustomerId FROM dbo.Orders WHERE OrderId &lt;= 50000;\n\nSELECT COUNT(*) FROM #recent AS r WHERE r.CustomerId = 1;</code></pre>\n<p>That scan was estimated at 5,000 rows.</p>\n<h3>Row goals: TOP and LIMIT</h3>\n<p>When a query asks for only the first few rows, the optimizer plans for stopping early. It assumes matching rows are spread evenly, so it expects to find ten of them after reading a small part of the table. If the matching rows all sit at the far end, it reads nearly everything first:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT order_id, total FROM orders\nWHERE order_date &gt;= '2025-04-01'\nORDER BY order_id LIMIT 10;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Limit  (cost=0.42..47.23 rows=10 width=10) (actual rows=10.00 loops=1)\n  -&gt;  Index Scan using orders_pkey on orders  (cost=0.42..29668.45 rows=6338 width=10) (actual rows=10.00 loops=1)\n        Filter: (order_date &gt;= '2025-04-01 00:00:00'::timestamp without time zone)\n        Rows Removed by Filter: 394079</code></pre>\n<p>The plan walks the primary key in order and throws away 394,079 rows before it finds ten that match. SQL Server marks an operator planned this way with <code>EstimateRowsWithoutRowGoal</code> in the plan XML, next to the reduced estimate.</p>\n<p>No statistic tells the optimizer where in the table the matching rows sit, so fresh statistics do not change this plan, and neither does an index on <code>order_date</code> by itself: the primary key walk still looks cheaper. What works is taking away the early stop. Fetch the matching rows first, then sort them:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_date_idx ON orders (order_date);\n\nEXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nWITH recent AS MATERIALIZED (\n    SELECT order_id, total FROM orders WHERE order_date &gt;= '2025-04-01'\n)\nSELECT order_id, total FROM recent ORDER BY order_id LIMIT 10;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Limit  (cost=5141.15..5141.17 rows=10 width=20) (actual rows=10.00 loops=1)\n    -&gt;  Bitmap Heap Scan on orders  (cost=108.95..4902.10 rows=5745 width=10) (actual rows=5921.00 loops=1)\n          Recheck Cond: (order_date &gt;= '2025-04-01 00:00:00'::timestamp without time zone)\n          -&gt;  Bitmap Index Scan on orders_date_idx  (cost=0.00..107.51 rows=5745 width=0) (actual rows=5921.00 loops=1)\n                Index Cond: (order_date &gt;= '2025-04-01 00:00:00'::timestamp without time zone)\n  -&gt;  Sort  (cost=239.05..253.41 rows=5745 width=20) (actual rows=10.00 loops=1)\n        Sort Key: recent.order_id\n        Sort Method: top-N heapsort  Memory: 25kB\n        -&gt;  CTE Scan on recent  (cost=0.00..114.90 rows=5745 width=20) (actual rows=5921.00 loops=1)</code></pre>","fix_html":"<h3>Refresh the statistics</h3>\n<p>This is the first thing to try and it is cheap. It fixes stale statistics and nothing else.</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>ANALYZE orders_copy;\n\nEXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT * FROM orders_copy WHERE order_date &gt;= '2026-01-01';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Seq Scan on orders_copy  (cost=0.00..9437.00 rows=45144 width=37) (actual rows=50000.00 loops=1)\n  Filter: (order_date &gt;= '2026-01-01 00:00:00'::timestamp without time zone)\n  Rows Removed by Filter: 400000</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>UPDATE STATISTICS dbo.Orders;</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>ANALYZE TABLE orders;</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>EXEC DBMS_STATS.GATHER_TABLE_STATS(USER, 'ORDERS');</code></pre>\n<p>If a table goes stale again and again, the automatic refresh is too slow for it. In PostgreSQL lower <a href=\"/sql-configuration/postgresql/autovacuum-analyze-scale-factor\">autovacuum_analyze_scale_factor</a> for that table; in SQL Server check <a href=\"/sql-configuration/sql-server/auto-update-statistics\">AUTO_UPDATE_STATISTICS</a>. The <a href=\"/sql-snippets/statistics-staleness\">statistics staleness snippet</a> lists every table that is behind.</p>\n<h3>Tell the optimizer about related columns</h3>\n<p>PostgreSQL extended statistics record how columns depend on each other:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE STATISTICS orders_customer_status_stx (dependencies, mcv)\n    ON customer_id, status FROM orders;\nANALYZE orders;\n\nEXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT * FROM orders WHERE customer_id = 1 AND status = 'pending';</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>-&gt;  Parallel Seq Scan on orders  (cost=0.00..6982.00 rows=1650 width=37) (actual rows=1333.33 loops=3)\n      Filter: ((customer_id = 1) AND ((status)::text = 'pending'::text))\n      Rows Removed by Filter: 132000</code></pre>\n<p>Oracle has the same idea as a column group. Ask for a histogram on the group, since the point is that some combinations are far more common than others:</p>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>SELECT DBMS_STATS.CREATE_EXTENDED_STATS(USER, 'ORDERS', '(customer_id, status)') FROM dual;\nEXEC DBMS_STATS.GATHER_TABLE_STATS(USER, 'ORDERS', method_opt =&gt; 'FOR ALL COLUMNS SIZE AUTO FOR COLUMNS (customer_id, status) SIZE 254', no_invalidate =&gt; FALSE);\n\nSELECT /*+ GATHER_PLAN_STATISTICS */ COUNT(*)\nFROM orders WHERE customer_id = 1 AND status = 'pending';\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(format =&gt; 'ALLSTATS LAST'));</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\" data-role=\"output\"><code>| Id  | Operation          | Name   | Starts | E-Rows | A-Rows |   A-Time   | Buffers |\n|   0 | SELECT STATEMENT   |        |      1 |        |      1 |00:00:00.01 |    2391 |\n|   1 |  SORT AGGREGATE    |        |      1 |      1 |      1 |00:00:00.01 |    2391 |\n|*  2 |   TABLE ACCESS FULL| ORDERS |      1 |   3300 |   4000 |00:00:00.01 |    2391 |</code></pre>\n<h3>MySQL: add a histogram</h3>\n<p>MySQL keeps value distributions only for indexed columns unless you ask. For a filter on a column without an index it assumes a fixed share of the table, which is where the 39,864 above came from: a tenth of the rows. A histogram gives it the real distribution:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>ANALYZE TABLE orders UPDATE HISTOGRAM ON status WITH 16 BUCKETS;\n\nEXPLAIN ANALYZE SELECT * FROM orders WHERE status = 'pending';</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Filter: (orders.`status` = 'pending')  (cost=40266 rows=4001) (actual time=0.0607..52.8 rows=4000 loops=1)\n    -&gt; Table scan on orders  (cost=40266 rows=399054) (actual time=0.0517..40.4 rows=400000 loops=1)</code></pre>\n<h3>Make the expression something statistics can cover</h3>\n<p>Rewrite the condition so the bare column is compared with a value (<code>total &gt; 100 / 1.2</code> instead of <code>total * 1.2 &gt; 100</code>). When the expression has to stay, PostgreSQL gathers statistics for an expression that has an index on it or its own <code>CREATE STATISTICS</code> entry:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE STATISTICS orders_total_gross_stx ON (total * 1.2) FROM orders;\nANALYZE orders;\n\nEXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)\nSELECT * FROM orders WHERE total * 1.2 &gt; 100;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Seq Scan on orders  (cost=0.00..10482.00 rows=336075 width=37) (actual rows=337547.00 loops=1)\n  Filter: ((total * 1.2) &gt; '100'::numeric)\n  Rows Removed by Filter: 62453</code></pre>\n<h3>When to leave it alone</h3>\n<p>An estimate that is off by a factor of two or three rarely changes the plan. A large miss also does not matter when the plan would be the same either way: a scan of a table that has to be scanned, or a wrong estimate on the last step with nothing above it. Chase a bad estimate when a join method, a join order or a memory grant above it looks wrong for the real row count.</p>","checklist_html":["Capture a plan with actual row counts, not an estimated plan.","Find the deepest operator where estimated and actual rows differ by ten times or more.","Check when statistics on that table were last gathered and how many rows changed since.","Refresh the statistics and capture the plan again.","If it is still wrong, look for related columns, an expression, a table variable or a TOP/LIMIT.","Add extended statistics, a histogram or an index that fits the filter.","Confirm the estimate moved and the plan above it changed."],"faqs":[{"question":"How far off does a row estimate have to be to matter?","answer":"A factor of ten is a common working threshold. What matters is whether the error crosses a point where the optimizer would choose differently: a nested loop planned for 10 rows that receives 100,000, or a sort given memory for 1,000 rows that receives a million."},{"question":"Why is the estimate wrong when statistics are up to date?","answer":"Because statistics describe one column at a time. Two filters on related columns, a calculation on a column, or a join to a row with far more matches than average all produce wrong estimates from correct statistics. Extended statistics, histograms and rewriting the expression address those cases."},{"question":"Why does the estimate say 1 row?","answer":"Usually the query asks for values outside the range the statistics have seen, such as rows newer than the last statistics refresh. The optimizer concludes almost nothing matches. Refreshing the statistics fixes it."},{"question":"Are table variables always estimated at one row?","answer":"Not since SQL Server 2019. With compatibility level 150 or higher, the statement that reads a table variable is compiled after the variable is filled, so the optimizer knows its row count. It still has no statistics on the columns, so filters and joins on the variable are guessed. A temporary table has full statistics."},{"question":"What is a row goal?","answer":"It is the optimizer planning for a query that will stop after a fixed number of rows, because of TOP, LIMIT, FETCH FIRST or EXISTS. It scales its estimates down to the rows it expects to read before stopping. When matching rows are not spread evenly, it can read far more than planned."}],"plan_group":"Row estimates and statistics","related_slugs":["parameter-sniffing","sudden-slowdown","join-algorithms"]},"source_url":"https://sqlly.app/sql-performance/row-estimate-mismatch","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/scalar-udf","corpus":"sql-performance","engine":null,"language":"en","title":"Scalar functions that run once per row","description":"A scalar user-defined function runs once per row, hides its reads and forces a serial plan. How to see it in the plan and three ways to remove it.","body":{"slug":"scalar-udf","engines":["SQL Server"],"symptoms":["Slow query","High CPU"],"h1":"Scalar functions that run once per row","lede":"A scalar user-defined function in a SQL Server query runs once for every row, keeps its own reads out of the plan and the I/O statistics, and stops the query from running in parallel. How to find it, and how to inline it or replace it.","symptom_html":"<p>A scalar user-defined function looks like a cheap call in the query text. In the plan it is a <code>Compute Scalar</code> with a tiny estimated cost. What SQL Server really does is run the function body as a separate statement for every row that reaches it. Whatever the function reads is missing from the plan and from <code>STATISTICS IO</code>, and the whole query runs on one thread.</p>\n<p>Since SQL Server 2019 the optimizer can inline many scalar functions into the calling query, which removes all three problems. It cannot inline every function, and inlining is off below compatibility level 150. The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> flags a function that was not inlined. The examples use a shop schema with 20,000 customers and 400,000 orders.</p>","diagnosis_html":"<h3>A query that looks cheap and is not</h3>\n<p>This function counts a customer's orders. <code>WITH INLINE = OFF</code> makes it behave the way every scalar function behaves below compatibility level 150, and the way a function that cannot be inlined behaves on any version:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);\nGO\nCREATE FUNCTION dbo.CustomerOrderCount (@CustomerId int)\nRETURNS int\nWITH INLINE = OFF\nAS\nBEGIN\n    RETURN (SELECT COUNT(*) FROM dbo.Orders WHERE CustomerId = @CustomerId);\nEND;\nGO\nSET STATISTICS IO ON;\nSET STATISTICS TIME ON;\nGO\nSELECT COUNT(*)\nFROM dbo.Customers AS c\nWHERE dbo.CustomerOrderCount(c.CustomerId) &gt; 20;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Customers'. Scan count 1, logical reads 115, physical reads 0\n CPU time = 606 ms, elapsed time = 637 ms.</code></pre>\n<p>The statistics list 115 page reads on <code>Customers</code> and nothing for <code>Orders</code>, although the function read that table 20,000 times. The CPU time, more than half a second for a query that reads 115 pages, is the only sign of it.</p>\n<h3>What the plan says</h3>\n<p>Capture the actual plan with <code>SET STATISTICS XML ON</code>, or with Include Actual Execution Plan in your client. Two things in the XML give the function away:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS XML ON;\nGO\nSELECT COUNT(*)\nFROM dbo.Customers AS c\nWHERE dbo.CustomerOrderCount(c.CustomerId) &gt; 20;\nGO\nSET STATISTICS XML OFF;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>&lt;QueryPlan DegreeOfParallelism=\"0\" NonParallelPlanReason=\"TSQLUserDefinedFunctionsNotParallelizable\"\n&lt;UserDefinedFunction FunctionName=\"[learnfx].[dbo].[CustomerOrderCount]\"&gt;</code></pre>\n<p>The <code>UserDefinedFunction</code> element sits inside a <code>Compute Scalar</code> or <code>Filter</code> operator. The <code>NonParallelPlanReason</code> on the root says the function is why the query ran on one thread; <a href=\"/sql-performance/parallel-query-plans\">parallel plans that do not run in parallel</a> lists the other reasons. (<code>learnfx</code> is the name of the test database.)</p>\n<h3>Count the calls</h3>\n<p><code>sys.dm_exec_function_stats</code> keeps the totals the query's own statistics leave out:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT OBJECT_NAME(object_id) AS function_name, execution_count,\n       total_worker_time, total_logical_reads\nFROM sys.dm_exec_function_stats\nWHERE database_id = DB_ID();</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>CustomerOrderCount 40000 1625467 161678</code></pre>\n<p>The columns are the function name, the number of executions, the CPU time in microseconds and the logical reads. The two runs above called the function 40,000 times. Each call is an index seek of a few pages, cheap on its own; the cost is paying for a separate statement 20,000 times per query.</p>\n<h3>Find out whether a function can be inlined</h3>\n<p>A function with a time-dependent call such as <code>GETDATE()</code> is one of the kinds that cannot be inlined. <code>sys.sql_modules</code> says so:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE FUNCTION dbo.OrderAgeDays (@OrderDate datetime2)\nRETURNS int\nAS\nBEGIN\n    RETURN DATEDIFF(day, @OrderDate, GETDATE());\nEND;\nGO\nSELECT o.name, m.is_inlineable, m.inline_type\nFROM sys.sql_modules AS m\nJOIN sys.objects AS o ON o.object_id = m.object_id\nWHERE o.type = 'FN'\nORDER BY o.name;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>CustomerOrderCount 1 0\nOrderAgeDays 0 0</code></pre>\n<p>The columns are the name, <code>is_inlineable</code> and <code>inline_type</code>. <code>CustomerOrderCount</code> could be inlined but has inlining turned off. <code>OrderAgeDays</code> cannot be inlined at all. Also check the two switches that apply to the whole database:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT name, value FROM sys.database_scoped_configurations\nWHERE name = 'TSQL_SCALAR_UDF_INLINING';\n\nSELECT compatibility_level FROM sys.databases WHERE name = DB_NAME();</code></pre>\n<p>Inlining needs the configuration set to 1 and a <a href=\"/sql-configuration/sql-server/compatibility-level\">compatibility level</a> of 150 or higher.</p>","fix_html":"<h3>Let SQL Server inline the function</h3>\n<p>If the function is inlineable and something switched inlining off, switch it back on. For a function created <code>WITH INLINE = OFF</code>, alter it without the option:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>ALTER FUNCTION dbo.CustomerOrderCount (@CustomerId int)\nRETURNS int\nAS\nBEGIN\n    RETURN (SELECT COUNT(*) FROM dbo.Orders WHERE CustomerId = @CustomerId);\nEND;\nGO\nSELECT COUNT(*)\nFROM dbo.Customers AS c\nWHERE dbo.CustomerOrderCount(c.CustomerId) &gt; 20;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Orders'. Scan count 20000, logical reads 64698, physical reads 0\nTable 'Customers'. Scan count 8, logical reads 340, physical reads 0\n CPU time = 186 ms, elapsed time = 30 ms.</code></pre>\n<p>The reads on <code>Orders</code> are now visible, the query ran in parallel, and the elapsed time fell from more than half a second to a few hundredths. In the plan XML the root element carries <code>ContainsInlineScalarTsqlUdfs=\"1\"</code> and the <code>UserDefinedFunction</code> element is gone.</p>\n<h3>Rewrite the function as an inline table-valued function</h3>\n<p>An inline table-valued function is a view with parameters. The optimizer expands it into the calling query on every version, with no compatibility level to depend on:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE FUNCTION dbo.CustomerOrderCounts (@CustomerId int)\nRETURNS TABLE\nAS\nRETURN (SELECT COUNT(*) AS OrderCount FROM dbo.Orders WHERE CustomerId = @CustomerId);\nGO\nSELECT COUNT(*)\nFROM dbo.Customers AS c\nCROSS APPLY dbo.CustomerOrderCounts(c.CustomerId) AS oc\nWHERE oc.OrderCount &gt; 20;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>Table 'Customers'. Scan count 1, logical reads 115, physical reads 0\nTable 'Orders'. Scan count 1, logical reads 701, physical reads 0</code></pre>\n<p>Here the optimizer went further than the inlined scalar function allowed: it read the index on <code>Orders</code> once, grouped it, and joined the result to <code>Customers</code>, in place of 20,000 separate seeks.</p>\n<h3>Replace a simple calculation with the expression</h3>\n<p>A function that only computes something from its arguments is usually better written out. The function version cannot be inlined because of <code>GETDATE()</code>:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT COUNT(*) FROM dbo.Orders WHERE dbo.OrderAgeDays(OrderDate) &gt; 1000;\n\nSELECT COUNT(*) FROM dbo.Orders WHERE DATEDIFF(day, OrderDate, GETDATE()) &gt; 1000;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>CPU time = 868 ms, elapsed time = 993 ms.\nCPU time = 38 ms, elapsed time = 38 ms.</code></pre>\n<p>Both read the same 2,579 pages. The first line is the function version: the call adds most of a second of CPU for 400,000 rows. Neither form can use an index on <code>OrderDate</code>; for that, compare the bare column with a computed date, as the <a href=\"/sql-performance/non-sargable-predicates\">non-sargable predicates guide</a> shows.</p>\n<h3>When to leave it alone</h3>\n<p>A scalar function called for a handful of rows costs nothing worth fixing: in the select list of a query that returns ten rows, or on a variable in a stored procedure. The same goes for a function the plan shows as inlined. Rewrite the ones that sit in a <code>WHERE</code> clause, a join condition or the select list of a query that handles many thousands of rows.</p>","checklist_html":["Look for a UserDefinedFunction element or a NonParallelPlanReason of TSQLUserDefinedFunctionsNotParallelizable in the plan XML.","Do not trust STATISTICS IO for this query; read the function's totals from sys.dm_exec_function_stats.","Check is_inlineable in sys.sql_modules for the function.","Check TSQL_SCALAR_UDF_INLINING and the database compatibility level (150 or higher).","Inlineable: remove WITH INLINE = OFF or turn inlining back on.","Not inlineable: rewrite it as an inline table-valued function with CROSS APPLY, or write the expression in the query.","Capture the plan again and confirm the function call is gone and the plan can go parallel."],"faqs":[{"question":"Why is a scalar user-defined function slow in SQL Server?","answer":"Unless it is inlined, SQL Server runs the function body as a separate statement for every row. A query over 400,000 rows makes 400,000 calls. The calls cannot be spread over several threads, so the whole query also runs serial."},{"question":"Why does STATISTICS IO show no reads for the table my function queries?","answer":"STATISTICS IO reports the reads of the calling statement only. Reads made inside a scalar function that was not inlined are left out, and the plan shows no operators for them. sys.dm_exec_function_stats has the real totals per function."},{"question":"What is scalar UDF inlining?","answer":"From SQL Server 2019, at compatibility level 150 or higher, the optimizer can replace a call to a scalar function with the function's logic, as if you had written a subquery. The reads then show in the plan and the query can run in parallel. Not every function qualifies; sys.sql_modules.is_inlineable shows which do."},{"question":"How do I know whether my function was inlined?","answer":"In the actual plan XML, an inlined call leaves ContainsInlineScalarTsqlUdfs=\"1\" on the QueryPlan element and no UserDefinedFunction element. A call that was not inlined shows the UserDefinedFunction element and a NonParallelPlanReason of TSQLUserDefinedFunctionsNotParallelizable."},{"question":"Is an inline table-valued function faster than a scalar function?","answer":"Usually, and on every version. An inline table-valued function is expanded into the calling query like a view, so the optimizer can join, group and parallelize across it. A scalar function gets that treatment only when it is inlineable and inlining is on."}],"plan_group":"Parallelism, functions and compile time","related_slugs":["parallel-query-plans","correlated-subquery","non-sargable-predicates"]},"source_url":"https://sqlly.app/sql-performance/scalar-udf","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/slow-query","corpus":"sql-performance","engine":null,"language":"en","title":"Diagnosing a slow SQL query","description":"A step-by-step method for a slow SQL query on any database: measure the time, read the execution plan, find the expensive step, and fix the access path.","body":{"slug":"slow-query","engines":["SQL Server","PostgreSQL","MySQL","SQLite","Oracle"],"symptoms":["Slow query"],"h1":"Diagnosing a slow SQL query","lede":"One query is slow, every time it runs. The same five steps work on SQL Server, PostgreSQL, MySQL, SQLite and Oracle: measure, get the real plan, find the expensive step, check the estimates, fix the access path.","symptom_html":"<p>This is the general method. Each engine has its own commands - the <a href=\"/sql-performance\">engine guides</a> cover them in detail - but the diagnosis is the same shape everywhere, and skipping a step is how people end up adding indexes that do not help.</p>","diagnosis_html":"<h3>Step 1: measure the query alone</h3>\n<p>Run it outside the app with timing on, and note three numbers: wall-clock time, rows returned, and how long the engine says it spent on CPU vs waiting. If it is fast standalone, the problem is the app (chatty N+1 queries, connection waits) or blocking - not this SQL.</p>\n<h3>Step 2: get the real plan, not the estimated one</h3>\n<p>Four of the five engines can execute the query and show what actually happened; only SQLite shows the plan without running it. The command per engine:</p>\n<h3>SQL Server: capture the actual plan and the reads</h3>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS IO, TIME ON;\nSET STATISTICS XML ON;   -- the actual plan comes back as an extra result set\n-- your query here</code></pre>\n<h3>PostgreSQL: run it under EXPLAIN with real numbers</h3>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>BEGIN;\nEXPLAIN (ANALYZE, BUFFERS)\nSELECT o.id, o.total FROM orders AS o WHERE o.status = 'pending';\nROLLBACK;</code></pre>\n<p>ANALYZE really executes the statement, hence the wrapper: on a write, the ROLLBACK undoes it. From PostgreSQL 18, BUFFERS comes with ANALYZE automatically (BUFFERS OFF turns it back off); earlier versions need it requested.</p>\n<h3>MySQL: run it under EXPLAIN ANALYZE</h3>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN ANALYZE\nSELECT o.order_id, o.total FROM orders AS o WHERE o.status = 'pending';</code></pre>\n<p>MySQL 8.0.18 and later print the tree with actual times, rows and loops beside the estimates; on older servers, plain <code>EXPLAIN</code> plus <code>SHOW WARNINGS</code> is the best available.</p>\n<h3>SQLite: read the plan, then time the query</h3>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>EXPLAIN QUERY PLAN\nSELECT order_id, total FROM orders WHERE status = 'pending';</code></pre>\n<p>No actual row counts here - the statement is not run. The <code>sqlite3</code> shell adds <code>.timer on</code> for wall-clock time and, in builds with scan-status support, <code>.scanstats on</code> for loops and rows per step.</p>\n<h3>Oracle: capture the plan after it ran</h3>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>SELECT /*+ gather_plan_statistics */ order_id, total\nFROM orders WHERE status = 'PENDING';\n\nSELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(NULL, NULL, 'ALLSTATS LAST'));</code></pre>\n<p>Run both in the same session; in SQL*Plus turn SERVEROUTPUT off first, or the last statement is not yours.</p>\n<h3>Step 3: find the most expensive step</h3>\n<p>Plans are trees; the cost concentrates in one or two nodes. The usual suspects: a <em>table scan</em> on a table with millions of rows, a <em>sort or hash</em> that spills to disk, a <em>nested loop</em> re-executing a lookup thousands of times, or a <em>filter</em> throwing away most of the rows it read.</p>\n<h3>Step 4: check the estimates on that step</h3>\n<p>Compare estimated rows with actual rows on the expensive node (per loop: PostgreSQL reports actual rows per loop, Oracle's A-Rows is the total over all starts). If they differ by 10x or more, the optimizer chose the plan from bad information. Refresh the statistics before adding an index, because a new index costed from the same bad estimate may not get used. If fresh statistics do not close the gap, the predicate itself is the problem: correlated columns, a function on the column, or a value the histogram cannot see.</p>\n<h3>Step 5: fix the access path the step wants</h3>\n<p>The expensive node tells you the fix: a scan wants an index whose leading columns match the predicate; a sort that spills to disk wants fewer or narrower rows going into it, more sort memory, or an index that already delivers the rows in order; a loop with thousands of probes wants the inner table's join column indexed. Make the change, re-run the plan, and confirm the node changed shape and the time dropped. Paste each plan into the <a href=\"/tools/query-plan-viewer\">query plan viewer</a> to read the operators and costs, and run messy SQL through the <a href=\"/tools/sql-formatter\">formatter</a> first so the plan's query matches what you think you wrote.</p>","fix_html":"<p>The fix follows from the expensive step, and it is almost always one of four things: an index, statistics, a rewrite, or nothing (the query returns a million rows and the engine is already doing it as cheaply as possible - the fix is returning fewer rows).</p>\n<p>For the commonest first fix, an index on the expensive scan's predicate, equality column first and range column last, the statement per engine for the pending-orders query above:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX idx_orders_status\nON dbo.Orders (Status) INCLUDE (Total);</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX CONCURRENTLY idx_orders_status\nON orders (status) INCLUDE (total);</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>ALTER TABLE orders\nADD INDEX idx_orders_status (status, total);</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>CREATE INDEX idx_orders_status\nON orders (status, total);</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>CREATE INDEX idx_orders_status\nON orders (status, total);</code></pre>\n<p>SQL Server and PostgreSQL 11 or later take INCLUDE columns, which never filter but save the table visit; elsewhere the columns join the key. Then re-run the capture from step 2 and confirm the expensive node changed shape and the time dropped.</p>\n<h3>When the fix is not an index</h3>\n<p>When the plan is already indexed and the estimates are honest, look at what the query asks for: <code>SELECT *</code> rows the app never reads, functions applied per row, or predicates in the application that could live in the WHERE clause. A rewrite that lets the engine filter early beats any index on a wide row. And a query that is fast standalone but slow in the app has a plan that is innocent - the N+1 pattern or the lock queue is the problem, not this SQL.</p>","checklist_html":["Run the query standalone with engine timing; confirm it is slow by itself.","Capture the actual (executed) plan, not the estimated one.","Identify the one or two most expensive nodes in the plan tree.","Compare estimated vs actual rows on those nodes; diverge means statistics first.","Add the index the scan asks for: equality columns first, range column last, INCLUDEs for the SELECT.","Re-run the plan and verify the expensive node changed shape.","Record before/after time and logical reads so the change is provable."],"faqs":[{"question":"The query is fast in the tool and slow in the app. Why?","answer":"Different plans from different sessions (settings that change the plan, like parameter types), blocking from other sessions, or the app issuing the query many more times than you think (N+1). Run the app's exact statement with the app's exact parameters, and check for lock waits while it runs."},{"question":"Should I just add a hint to force a better plan?","answer":"Rarely. A hint pins the plan to today's data shape; when the data changes, the hint keeps forcing yesterday's plan. Add the index or fix the statistics the optimizer is missing first, and treat hints as a last resort you document."},{"question":"How do I tell CPU cost from I/O cost in a slow query?","answer":"Read the engine's counters: CPU time vs elapsed time from SET STATISTICS TIME on SQL Server, the BUFFERS counts on PostgreSQL, rows examined in the slow log or the Handler_read% status counters on MySQL, Buffers and A-Time in DBMS_XPLAN on Oracle. Elapsed far above CPU means the query is waiting (disk, locks, the network). High CPU with few reads means functions, sorts or row-by-row work; high reads means the access path. They lead to different fixes."},{"question":"When is a slow query not the query's fault?","answer":"When the plan is a seek, the estimates match, and the reads are low but it still takes seconds: it is waiting, not working. Check for locks, log flush waits, or a saturated server - see the blocking and high CPU guides for those paths."},{"question":"Where can I compare two plans?","answer":"The free web plan viewer at /tools/query-plan-viewer reads one plan at a time (SQL Server XML, PostgreSQL and MySQL EXPLAIN, SQLite EXPLAIN QUERY PLAN, Oracle DBMS_XPLAN), so open the before and after plans in two browser tabs. The SQLly desktop app keeps the plans captured in each query tab and compares any two of them, listing the operators that regressed, improved, appeared or disappeared."}],"plan_group":null,"related_slugs":[]},"source_url":"https://sqlly.app/sql-performance/slow-query","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/sort-and-hash-spills","corpus":"sql-performance","engine":null,"language":"en","title":"Sorts and hashes that spill to disk","description":"A sort or hash that runs out of memory continues on disk, many times slower. How each engine reports the spill and how to fix it without wasting memory.","body":{"slug":"sort-and-hash-spills","engines":["PostgreSQL","SQL Server","MySQL"],"symptoms":["Slow query","Memory pressure"],"h1":"Sorts and hashes that spill to disk","lede":"Sorts, hash joins and hash aggregates work in memory until the memory they were given runs out, then continue in temporary files. How PostgreSQL, SQL Server and MySQL report a spill, what causes it, and how to give the operation enough memory or less to do.","symptom_html":"<p>Sorts, hash joins and hash aggregates need working memory in proportion to the rows they handle. Each engine caps that memory. When an operation needs more than its cap, it does not fail: it writes part of its data to temporary files and works through them in passes. The query still returns the right answer, only slower, and it now depends on the speed of the temp disk.</p>\n<p>There are two causes, with different fixes. Either the cap is too small for an honest workload, or the engine expected far fewer rows than arrived and reserved too little. The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> reports spills with the amount written to disk. The examples use a shop schema with 400,000 orders and 800,000 order items.</p>","diagnosis_html":"<h3>PostgreSQL: Sort Method and Batches</h3>\n<p>A sort that stayed in memory reports <code>quicksort</code> with <code>Memory</code>. One that spilled reports <code>external merge</code> with <code>Disk</code>. With <code>BUFFERS</code>, the temp file traffic shows up as <code>temp read</code> and <code>written</code>:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, SUMMARY OFF)\nSELECT * FROM orders ORDER BY total;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Sort  (cost=56638.78..57638.78 rows=400000 width=37) (actual rows=400000.00 loops=1)\n  Sort Key: total\n  Sort Method: external merge  Disk: 19120kB\n  Buffers: shared hit=4485, temp read=2390 written=2397</code></pre>\n<p>A hash join that did not fit splits its input into batches and processes them one at a time. <code>Batches: 1</code> means it fit; anything higher went to disk:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SET max_parallel_workers_per_gather = 0;\n\nEXPLAIN (ANALYZE, BUFFERS, TIMING OFF, SUMMARY OFF)\nSELECT o.customer_id, count(*)\nFROM orders AS o\nJOIN order_items AS i ON i.order_id = o.order_id\nGROUP BY o.customer_id;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>-&gt;  Hash Join  (cost=15045.00..38054.02 rows=800000 width=4) (actual rows=800000.00 loops=1)\n            Buckets: 262144  Batches: 4  Memory Usage: 5954kB\n            Buffers: shared hit=4482, temp written=1024</code></pre>\n<p>A hash aggregate reports <code>Disk Usage</code> the same way:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>EXPLAIN (ANALYZE, BUFFERS OFF, TIMING OFF, SUMMARY OFF)\nSELECT product_id, order_id, count(*)\nFROM order_items\nGROUP BY product_id, order_id;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>HashAggregate  (cost=60096.00..69843.73 rows=349773 width=16) (actual rows=800000.00 loops=1)\n  Planned Partitions: 4  Batches: 21  Memory Usage: 8505kB  Disk Usage: 19928kB</code></pre>\n<p>That plan also shows the other cause: the planner expected about 350,000 groups and got 800,000. To find spills across the whole server, <a href=\"/sql-configuration/postgresql/log-temp-files\">log_temp_files</a> writes every temp file above a size to the log, and the <a href=\"/sql-snippets/temp-table-spilling\">temp spilling snippet</a> reads the totals per database.</p>\n<h3>Lossy bitmap heap scans</h3>\n<p>A bitmap scan has the same limit. The bitmap normally records each matching row. When it outgrows <code>work_mem</code> it degrades to recording only which pages contain matches, and the scan must then re-test every row on those pages. The plan reports those pages as <code>lossy</code>:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>CREATE INDEX orders_customer_idx ON orders (customer_id);\nSET work_mem = '64kB';\n\nEXPLAIN (ANALYZE, BUFFERS OFF, TIMING OFF, SUMMARY OFF)\nSELECT sum(total) FROM orders WHERE customer_id BETWEEN 2 AND 600;\n\nRESET work_mem;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>-&gt;  Bitmap Heap Scan on orders  (cost=147.76..9962.29 rows=10472 width=6) (actual rows=10800.00 loops=1)\n      Recheck Cond: ((customer_id &gt;= 2) AND (customer_id &lt;= 600))\n      Rows Removed by Index Recheck: 90318\n      Heap Blocks: exact=551 lossy=1045\n      -&gt;  Bitmap Index Scan on orders_customer_idx  (cost=0.00..145.14 rows=10472 width=0) (actual rows=10800.00 loops=1)</code></pre>\n<p>Nothing is written to disk here; the cost is the extra rows read and rechecked. A few lossy pages are harmless. When most pages are lossy the fix is the same as for a spill: more <code>work_mem</code> for that query.</p>\n<h3>SQL Server: spill warnings and the memory grant</h3>\n<p>SQL Server decides how much memory a query gets before it starts, from the estimated row counts. That reservation is the memory grant. If more rows arrive than estimated, the sort or hash spills to tempdb, and the actual plan carries a warning on the operator. A procedure compiled for a small customer and run for a large one shows it:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);\nGO\nCREATE OR ALTER PROCEDURE dbo.CustomerOrdersByTotal @CustomerId int\nAS\nSELECT OrderId, Total, Reference, OrderDate\nFROM dbo.Orders WHERE CustomerId = @CustomerId\nORDER BY Total DESC;\nGO\nSET NOCOUNT ON;\nGO\nEXEC dbo.CustomerOrdersByTotal @CustomerId = 4242;\nGO\nSET STATISTICS XML ON;\nGO\nEXEC dbo.CustomerOrdersByTotal @CustomerId = 1;\nGO\nSET STATISTICS XML OFF;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sql-server\" data-role=\"output\"><code>&lt;SpillToTempDb SpillLevel=\"1\" SpilledThreadCount=\"1\" /&gt;\n&lt;SortSpillDetails GrantedMemoryKb=\"1024\" UsedMemoryKb=\"1024\" WritesToTempDb=\"171\" ReadsFromTempDb=\"171\" /&gt;</code></pre>\n<p>The sort was granted 1,024 KB because the plan expected 20 rows, and 40,000 arrived. Management Studio draws this as a yellow warning triangle on the Sort operator. The grant for the whole query is on the root operator under <code>MemoryGrantInfo</code>, where <code>GrantedMemory</code> and <code>MaxUsedMemory</code> show what was reserved and what was used.</p>\n<p>The opposite problem has the same root. When the estimate is far too high, the query reserves memory it never touches, and other queries wait for memory that is sitting idle. Queries currently holding or waiting for a grant are listed in a view:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT session_id, requested_memory_kb, granted_memory_kb, used_memory_kb, wait_time_ms\nFROM sys.dm_exec_query_memory_grants\nORDER BY requested_memory_kb DESC;</code></pre>\n<p>The <a href=\"/sql-snippets/session-memory-grants\">session memory grants snippet</a> adds the query text.</p>\n<h3>MySQL: Sort_merge_passes</h3>\n<p>MySQL sorts in a buffer of <code>sort_buffer_size</code> bytes per session. A sort that does not fit is written out in chunks that are merged afterwards, and each merge is counted in a status variable:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>SET SESSION sort_buffer_size = 32768;\nFLUSH STATUS;\n\nSELECT COUNT(*) FROM (\n    SELECT order_id, total FROM orders ORDER BY total, reference LIMIT 400000\n) AS sorted;\n\nSHOW SESSION STATUS LIKE 'Sort_merge_passes';</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>| Sort_merge_passes | 97    |</code></pre>\n<p>The server-wide counter (<code>SHOW GLOBAL STATUS LIKE 'Sort_merge_passes'</code>) tells you whether sorts spill in normal operation. A value that keeps climbing means they do.</p>","fix_html":"<h3>Fix the row estimate first</h3>\n<p>If the plan expected far fewer rows than it got, more memory is the wrong fix: the engine will under-reserve again on the next query. Go to the operator where estimated and actual rows part ways and fix that, as described under <a href=\"/sql-performance/row-estimate-mismatch\">row estimate mismatch</a>. In the SQL Server example the cause is a plan compiled for a different parameter value, which is <a href=\"/sql-performance/parameter-sniffing\">parameter sniffing</a>.</p>\n<h3>Give the operation less to do</h3>\n<p>Memory use follows rows times row width. Select only the columns you need instead of <code>*</code>, filter before the sort or join, and check whether an index can deliver the order so that no sort is needed at all (see <a href=\"/sql-performance/expensive-sort\">expensive sorts</a>).</p>\n<h3>PostgreSQL: raise work_mem for the query</h3>\n<p><a href=\"/sql-configuration/postgresql/work-mem\">work_mem</a> is the cap for each sort or hash operation, not for the query or the server: one query can use it several times over, and every connection can do so at once. Raise it for the session or transaction that needs it and leave the server default modest:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SET work_mem = '64MB';\n\nEXPLAIN (ANALYZE, BUFFERS, TIMING OFF, SUMMARY OFF)\nSELECT * FROM orders ORDER BY total;\n\nRESET work_mem;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\" data-role=\"output\"><code>Sort  (cost=45701.28..46701.28 rows=400000 width=37) (actual rows=400000.00 loops=1)\n  Sort Key: total\n  Sort Method: quicksort  Memory: 34257kB\n  Buffers: shared hit=4482</code></pre>\n<p>Hash operations get <code>work_mem</code> multiplied by <a href=\"/sql-configuration/postgresql/hash-mem-multiplier\">hash_mem_multiplier</a>. Note that the in-memory sort used more memory than the on-disk one used disk; the two formats differ, so size <code>work_mem</code> from the <code>Memory</code> figure of a run that fit, not from the <code>Disk</code> figure.</p>\n<h3>MySQL: raise sort_buffer_size for the session</h3>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>SET SESSION sort_buffer_size = 64 * 1024 * 1024;\nFLUSH STATUS;\n\nSELECT COUNT(*) FROM (\n    SELECT order_id, total FROM orders ORDER BY total, reference LIMIT 400000\n) AS sorted;\n\nSHOW SESSION STATUS LIKE 'Sort_merge_passes';</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>| Sort_merge_passes | 0     |</code></pre>\n<p>As with PostgreSQL, set it per session for the queries that need it. <a href=\"/sql-configuration/mysql/sort-buffer-size\">sort_buffer_size</a> is allocated per sort, so a large global value multiplies across connections.</p>\n<h3>SQL Server: correct the grant</h3>\n<p>Once the estimate is right the grant follows. Where it cannot be fixed, <code>OPTION (RECOMPILE)</code> gives each call a grant sized for its own values:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>CREATE OR ALTER PROCEDURE dbo.CustomerOrdersByTotal @CustomerId int\nAS\nSELECT OrderId, Total, Reference, OrderDate\nFROM dbo.Orders WHERE CustomerId = @CustomerId\nORDER BY Total DESC\nOPTION (RECOMPILE);\nGO\nSET NOCOUNT ON;\nSET STATISTICS XML ON;\nGO\nEXEC dbo.CustomerOrdersByTotal @CustomerId = 1;</code></pre>\n<p>On our test server this run had no spill warning. For a query that reserves far more than it uses, the <code>MAX_GRANT_PERCENT</code> query hint caps the grant.</p>\n<h3>When to leave it alone</h3>\n<p>A spill of a few megabytes on a query that runs once a night is not worth a setting change. Large sorts for reports and index builds are expected to use disk. Act when the spill is on a frequent query, when temp reads make up much of its run time, or when the cause is a wrong estimate that is also distorting the rest of the plan.</p>","checklist_html":["Look for external merge, Batches above 1 or Disk Usage (PostgreSQL), a spill warning (SQL Server), or Sort_merge_passes (MySQL).","Compare estimated and actual rows on the spilling operator.","If the estimate is wrong, fix the estimate before touching memory settings.","Trim the columns and rows that reach the sort or hash.","Raise work_mem or sort_buffer_size for the session that runs the query, not for the server.","Capture the plan again and confirm the operation now runs in memory."],"faqs":[{"question":"What does external merge Disk mean in PostgreSQL?","answer":"The sort needed more than work_mem, so PostgreSQL wrote sorted runs to temporary files and merged them. The Disk figure is the temp space used. The same sort with enough work_mem reports quicksort and a Memory figure instead."},{"question":"What does Batches mean on a Hash node?","answer":"It is the number of pieces the hash join split its input into. Batches: 1 means the whole hash table fit in memory. A higher number means the join wrote the other batches to temp files and processed them one after another."},{"question":"How much work_mem should I set?","answer":"Enough for the operation that spills, set for the session or transaction that runs it. The limit applies per sort or hash node, and every connection can use it at the same time, so a high server-wide value can exhaust memory under load."},{"question":"What is a memory grant in SQL Server?","answer":"It is the memory reserved for a query's sorts and hashes before it starts, sized from the estimated row counts. Too small and the query spills to tempdb. Too large and the memory is held unused while other queries wait for their own grants."},{"question":"What are lossy heap blocks?","answer":"They are pages a PostgreSQL bitmap scan could only remember as a whole, because the bitmap would not fit in work_mem with one bit per row. Every row on a lossy page is read and re-tested against the condition, which shows as Rows Removed by Index Recheck."}],"plan_group":"Sorts, memory and temp space","related_slugs":["expensive-sort","row-estimate-mismatch","memory-pressure"]},"source_url":"https://sqlly.app/sql-performance/sort-and-hash-spills","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/sql-server","corpus":"sql-performance","engine":null,"language":"en","title":"SQL Server query performance troubleshooting","description":"Find slow SQL Server queries with wait stats, Query Store and execution plans, then fix missing indexes, bad estimates and parameter sniffing.","body":{"slug":"sql-server","engines":["SQL Server"],"symptoms":["Slow query","High CPU","Blocking and deadlocks","Memory pressure"],"h1":"SQL Server query performance troubleshooting","lede":"A method for slow SQL Server queries: read the waits, find the statements that cost the most, get the actual plan, and fix what it shows - missing indexes, stale statistics or a plan that only works for some parameter values.","symptom_html":"<p>The query is slow on SQL Server - a report takes minutes, an OLTP point lookup takes seconds, or the whole instance feels heavy. The server-wide DMVs below need <code>VIEW SERVER STATE</code> (on SQL Server 2022 and later, <code>VIEW SERVER PERFORMANCE STATE</code> is enough); the <code>sys.dm_db_*</code> views need <code>VIEW DATABASE STATE</code> in the database you are looking at.</p>","diagnosis_html":"<h3>Start with the waits</h3>\n<p>Waits tell you what the instance is short of before you open a single plan. Most rows in <code>sys.dm_os_wait_stats</code> are background threads idling, so filter them out or they fill the top of the list:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT TOP 15 wait_type,\nCAST(wait_time_ms / 1000.0 AS decimal(12, 1)) AS wait_s,\nCAST(100.0 * wait_time_ms / SUM(wait_time_ms) OVER () AS decimal(5, 1)) AS pct,\nwaiting_tasks_count,\nwait_time_ms / NULLIF(waiting_tasks_count, 0) AS avg_wait_ms\nFROM sys.dm_os_wait_stats\nWHERE waiting_tasks_count &gt; 0\nAND wait_type NOT LIKE N'%SLEEP%'\nAND wait_type NOT LIKE N'%QUEUE%'\nAND wait_type NOT LIKE N'XE[_]%'\nAND wait_type NOT LIKE N'BROKER[_]%'\nAND wait_type NOT LIKE N'QDS[_]%'\nAND wait_type NOT IN (\nN'SOS_WORK_DISPATCHER', N'CHECKPOINT_QUEUE', N'DIRTY_PAGE_POLL',\nN'REQUEST_FOR_DEADLOCK_SEARCH', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',\nN'HADR_TIMER_TASK', N'HADR_WORK_QUEUE', N'CLR_AUTO_EVENT',\nN'CLR_MANUAL_EVENT', N'WAITFOR', N'ONDEMAND_TASK_QUEUE',\nN'FT_IFTS_SCHEDULER_IDLE_WAIT', N'PWAIT_ALL_COMPONENTS_INITIALIZED',\nN'PWAIT_EXTENSIBILITY_CLEANUP_TASK')\nORDER BY wait_time_ms DESC;</code></pre>\n<p>The numbers are cumulative since the last restart, so a bad hour last month still counts. Run it twice a few minutes apart during the slowdown and compare. How to read the top rows: <code>PAGEIOLATCH_SH</code> means sessions are waiting for data pages to come from disk; <code>SOS_SCHEDULER_YIELD</code> means CPU-bound threads using up their scheduler quantum; <code>CXPACKET</code> is parallel queries (<code>CXCONSUMER</code> is the mostly harmless half of it); <code>LCK_M_*</code> is blocking; <code>WRITELOG</code> is commit latency on the transaction log; <code>RESOURCE_SEMAPHORE</code> is queries waiting for a memory grant; <code>ASYNC_NETWORK_IO</code> usually means the client is reading results slowly, not that the server is slow. If an unfamiliar wait sits on top with a huge <code>avg_wait_ms</code> and nothing else looks wrong, it is probably another idle wait for the exclusion list.</p>\n<h3>Find the statements that cost the most</h3>\n<p>Query Store keeps plans and runtimes across restarts. It is on by default for new databases from SQL Server 2022; on older versions, or on databases restored from them, turn it on:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>ALTER DATABASE [MyDb] SET QUERY_STORE = ON;\n\nSELECT TOP 10 q.query_id, p.plan_id,\nSUM(rs.count_executions) AS executions,\nCAST(SUM(rs.avg_duration * rs.count_executions) / 1000.0 AS decimal(18, 1)) AS total_ms,\nCAST(SUM(rs.avg_cpu_time * rs.count_executions) / 1000.0 AS decimal(18, 1)) AS cpu_ms,\nLEFT(qt.query_sql_text, 80) AS query_text\nFROM sys.query_store_runtime_stats AS rs\nJOIN sys.query_store_plan AS p ON p.plan_id = rs.plan_id\nJOIN sys.query_store_query AS q ON q.query_id = p.query_id\nJOIN sys.query_store_query_text AS qt ON qt.query_text_id = q.query_text_id\nGROUP BY q.query_id, p.plan_id, qt.query_sql_text\nORDER BY total_ms DESC;</code></pre>\n<p>Durations in Query Store are in microseconds, hence the division. One <code>query_id</code> with two <code>plan_id</code> rows and very different times is a plan regression. Without Query Store history, the plan cache answers the same question for whatever is still cached:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT TOP 10\nqs.total_elapsed_time / 1000 AS elapsed_ms,\nqs.total_worker_time / 1000 AS cpu_ms,\nqs.execution_count,\nSUBSTRING(st.text, (qs.statement_start_offset / 2) + 1,\n((CASE qs.statement_end_offset\n WHEN -1 THEN DATALENGTH(st.text)\n ELSE qs.statement_end_offset\nEND - qs.statement_start_offset) / 2) + 1) AS sql_text\nFROM sys.dm_exec_query_stats AS qs\nCROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st\nORDER BY qs.total_elapsed_time DESC;</code></pre>\n<h3>Get the actual plan and the I/O</h3>\n<p>For the query in hand, run it and collect what actually happened. The estimated plan only shows the optimizer's guesses, and the guesses are usually what went wrong:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SET STATISTICS IO, TIME ON;\nSET STATISTICS XML ON;   -- returns the actual plan as an extra result set\n-- your query here</code></pre>\n<p>The messages output gives logical reads per table plus CPU and elapsed time; the actual plan (or Include Actual Execution Plan in SSMS) gives actual row counts per operator. Look for the operator whose actual rows dwarf its estimate: that is where the optimizer was guessing wrong. Save the plan XML and open it in the <a href=\"/tools/query-plan-viewer\">free query plan viewer</a> to see the costs without SSMS; if the SQL itself is hard to read, the <a href=\"/tools/sql-formatter\">SQL formatter</a> tidies it first. The SQLly desktop app also opens <code>.sqlplan</code> files in its own plan viewer.</p>\n<h3>Check the missing-index hints and the index usage</h3>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT TOP 10 d.statement, d.equality_columns, d.inequality_columns,\nd.included_columns, gs.user_seeks, gs.avg_user_impact\nFROM sys.dm_db_missing_index_details AS d\nJOIN sys.dm_db_missing_index_groups AS g\nON g.index_handle = d.index_handle\nJOIN sys.dm_db_missing_index_group_stats AS gs\nON gs.group_handle = g.index_group_handle\nORDER BY gs.avg_total_user_cost * gs.avg_user_impact * (gs.user_seeks + gs.user_scans) DESC;</code></pre>\n<p>Treat these as hints, not orders - the DMV cannot consolidate overlapping suggestions, lists columns in table order rather than the best key order, knows nothing about write cost, and empties on every restart. The mirror question matters too: <code>sys.dm_db_index_usage_stats</code> shows which indexes are never sought or scanned, and every unused index is a tax on every insert.</p>","fix_html":"<p>Most slow SQL Server queries come down to one of four fixes, in this order:</p>\n<p><strong>Add the index the plan asked for.</strong> Build it with the equality columns as keys, inequality columns next, and the columns the SELECT touches as INCLUDEs so the plan stops doing Key Lookups. One index that covers the overlapping suggestions beats the three near-duplicates the DMV lists.</p>\n<p><strong>Refresh stale statistics.</strong> Bad estimates come from stats sampled long before the data changed:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>UPDATE STATISTICS dbo.Orders WITH FULLSCAN;</code></pre>\n<p><strong>Deal with parameter sniffing on its own terms.</strong> If the cached plan is perfect for one parameter value and terrible for another, <code>OPTION (RECOMPILE)</code> on the offending statement is often the cheapest correct answer, as long as the statement does not run thousands of times a second. Query Store can also force the plan that behaves well for the common case (<code>sp_query_store_force_plan</code>), and at compatibility level 160 (SQL Server 2022) Parameter Sensitive Plan optimization can cache more than one plan for a skewed equality predicate on its own.</p>\n<p><strong>Stop the bleeding from blocking.</strong> If waits show <code>LCK_M_*</code>, the slow query may be a victim, not a cause - the <a href=\"/sql-performance/blocking-deadlocks\">blocking and deadlocks guide</a> covers finding and fixing the writer it waits behind.</p>\n<h3>When the four fixes do not apply</h3>\n<p>Some waits name a different guide: <code>RESOURCE_SEMAPHORE</code> and <code>PAGEIOLATCH_*</code> point at memory and disk, and the <a href=\"/sql-performance/memory-pressure\">memory pressure guide</a> is the one to work through. A statement that runs in 2 ms but appears in the top ten by total time is a call-volume problem: the fix is in the application's loop, not in the plan. Query Store has nothing to show on a database where it was only just switched on, so fall back to the plan-cache query until history accumulates. And be careful with <code>OPTION (RECOMPILE)</code> on statements that run thousands of times a second - the compile cost can exceed what the better plan saves.</p>","checklist_html":["Run the wait-stats query and name the top wait: CPU, I/O, lock or log.","Identify the 3 statements with the highest total elapsed time from Query Store or the plan cache.","Run the worst one with SET STATISTICS IO, TIME ON and the actual execution plan.","Compare estimated vs actual rows on the most expensive operator; if they diverge by orders of magnitude, refresh statistics first.","Create one covering index for the dominant seek, keyed on the equality predicate.","Re-run and record: logical reads before and after, and elapsed time.","Re-check sys.dm_db_index_usage_stats a week later and drop indexes nothing uses."],"faqs":[{"question":"Where do I start when everything on the server is slow?","answer":"Start with sys.dm_os_wait_stats, not with a plan. The dominant wait tells you whether the problem is CPU, disk I/O, blocking or the log, and that decides which of the four fixes applies. If the top wait is LCK_M_*, a slow report is often just waiting on another session."},{"question":"Are the missing-index DMV suggestions safe to create?","answer":"They are directions, not scripts. The DMV suggests one index per query shape and cannot merge overlapping suggestions, so blindly creating all of them leaves you with near-duplicate indexes that slow down every write. Take the top suggestion, consolidate the similar ones into a single index with INCLUDE columns, and measure."},{"question":"Does an execution plan with a warning always mean a problem?","answer":"Not always, but always look. The common warnings - implicit conversion, spill to tempdb, missing join predicate - each cost real time on large inputs, and each has a targeted fix: a cast that matches the column type, an index that keeps the sort in memory, or a predicate that was lost in the WHERE clause."},{"question":"How often should statistics be updated?","answer":"Let auto-update handle most tables and intervene where it is known to lag. Since compatibility level 130 (SQL Server 2016) the auto-update threshold on large tables is roughly SQRT(1000 x rows) modified rows instead of 20%, so big tables refresh far more often than they used to, but the refresh is sampled. Ascending key columns like order dates still fall behind: new rows land past the last histogram step, where the estimate is a guess (the legacy cardinality estimator guesses 1 row). A scheduled UPDATE STATISTICS ... WITH FULLSCAN on the handful of hot tables fixes most estimate problems without touching the rest."},{"question":"Can I see execution plans without installing SSMS?","answer":"Yes. Save the plan as a .sqlplan file or paste the plan XML into SQLly's free web plan viewer at /tools/query-plan-viewer - it runs entirely in your browser. The SQLly desktop app has the same viewer built in next to the query editor."}],"plan_group":null,"related_slugs":[]},"source_url":"https://sqlly.app/sql-performance/sql-server","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/sqlite","corpus":"sql-performance","engine":null,"language":"en","title":"SQLite query performance troubleshooting","description":"Speed up SQLite queries with EXPLAIN QUERY PLAN: turn SCAN into SEARCH with the right index, order index columns correctly, and ANALYZE.","body":{"slug":"sqlite","engines":["SQLite"],"symptoms":["Slow query","Bad index usage"],"h1":"SQLite query performance troubleshooting","lede":"SQLite is fast when the plan is a SEARCH and slow when it is a SCAN. How to read EXPLAIN QUERY PLAN, build the index the query needs, and keep the planner informed.","symptom_html":"<p>A query that was instant on small data takes seconds once the table grew. SQLite has no server, no statistics daemon and no plan cache to tune - performance here is almost entirely about the query plan, and there is exactly one command you need to see it.</p>","diagnosis_html":"<h3>Read the plan: SCAN is the smell, SEARCH is the goal</h3>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>EXPLAIN QUERY PLAN\nSELECT id, total FROM orders\nWHERE customer_id = 42 AND status = 'pending';</code></pre>\n<p>Output like <code>SCAN orders</code> means SQLite reads every row of the table. <code>SEARCH orders USING INDEX idx_orders_customer_status (customer_id=? AND status=?)</code> means it seeks, and the part in brackets shows which index columns the seek used. Most of this page is about turning the first into the second. EXPLAIN QUERY PLAN does not run the query, so it has no actual row counts. For those, the <code>sqlite3</code> shell has <code>.timer on</code> for wall-clock time and, in builds with scan-status support (the standard shell from recent releases has it), <code>.scanstats on</code>, which prints loops and rows per plan step after each query. <code>.eqp on</code> shows the plan above every query automatically.</p>\n<h3>Build the index the query asks for</h3>\n<p>SQLite uses a multi-column index from the left. The example above wants equality columns in any order (both are equalities), with range columns after them:</p>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>CREATE INDEX idx_orders_customer_status\nON orders (customer_id, status);</code></pre>\n<p>When the SELECT lists only indexed columns, SQLite skips the table entirely - a covering index shows up in the plan as <code>USING COVERING INDEX</code>. Adding <code>total</code> to the index above would make the query index-only.</p>\n<h3>Give the planner real statistics</h3>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>ANALYZE;\nSELECT * FROM sqlite_stat1;</code></pre>\n<p><code>ANALYZE</code> records, per index, the row count and the average number of rows per distinct key prefix in <code>sqlite_stat1</code> (a row like <code>20000 20 1</code>). The planner uses those numbers to pick between two candidate indexes, or between an index and a scan. Without them it assumes every index is fairly selective. For an app that ships a database file, <code>PRAGMA optimize;</code> before closing a connection runs ANALYZE only where the statistics look out of date, and is the approach the SQLite docs recommend.</p>\n<h3>Watch for the quiet killers</h3>\n<p>A <code>LIKE '%abc'</code> filter cannot use any B-tree index. Less obviously, <code>LIKE 'abc%'</code> cannot use a plain index either, because SQLite's LIKE is case-insensitive by default: it needs an index declared <code>COLLATE NOCASE</code> on that column, or use <code>GLOB 'abc*'</code> (case-sensitive), which can seek a normal index. A function around a column (<code>WHERE lower(email) = ...</code>) blocks the index unless you build an index on the same expression (<code>CREATE INDEX ... ON orders(lower(email))</code>), and an <code>ORDER BY</code> that no index satisfies forces a full sort per run. Each shows up as a SCAN or a <code>USE TEMP B-TREE</code> line in the plan. To inspect the SQL that produced the plan - pasted in from a log or an ORM - the <a href=\"/tools/sql-formatter\">SQL formatter</a> lays it out clause by clause; the plan tree itself also reads well in the <a href=\"/tools/query-plan-viewer\">query plan viewer</a>.</p>","fix_html":"<p><strong>Add the index whose prefix matches the predicate</strong>, equality columns first, range column last, and re-run EXPLAIN QUERY PLAN until the SCAN became a SEARCH. That one loop fixes most slow SQLite queries.</p>\n<p><strong>Prefer covering indexes on hot paths.</strong> Mobile apps and embedded devices pay real I/O costs for heap pages, so keeping the query entirely inside the index is worth the extra bytes:</p>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>CREATE INDEX idx_orders_cover\nON orders (customer_id, status, created_at, total);</code></pre>\n<p><strong>Run ANALYZE after big data changes</strong> - imports, migrations, bulk deletes - or <code>PRAGMA optimize</code> on a schedule, so the planner is not choosing from stale numbers.</p>\n<p><strong>Keep writes from starving reads.</strong> SQLite allows one writer at a time. Outside a transaction every INSERT is its own transaction with its own sync to disk, so wrap bulk inserts in a transaction per few thousand rows - SQLite can do tens of thousands of inserts a second but only dozens of separate transactions. In the default rollback-journal mode a writer also blocks readers while it commits; <code>PRAGMA journal_mode=WAL</code> lets readers carry on during writes, and the setting is stored in the database file. Set <code>PRAGMA busy_timeout</code> so a connection waits for the lock instead of failing at once with SQLITE_BUSY. If a query blocks rather than runs slow, the <a href=\"/sql-performance/blocking-deadlocks\">blocking guide's</a> short-transactions advice applies to SQLite too.</p>","checklist_html":["Run EXPLAIN QUERY PLAN on the slow query; note every SCAN line.","Check each SCAN's WHERE predicate for a matching index prefix.","Create the index with equality columns first and the range column last.","Re-run the plan and confirm SCAN became SEARCH (USING INDEX ...).","If the SELECT touches few columns, extend the index to cover the query.","Run ANALYZE after bulk loads (or PRAGMA optimize periodically) so sqlite_stat1 reflects the data.","Search the plan for USE TEMP B-TREE: an ORDER BY or GROUP BY no index satisfies.","Enable WAL mode and set busy_timeout if readers and writers queue behind each other."],"faqs":[{"question":"Does SQLite really need ANALYZE?","answer":"Not always. Without sqlite_stat1 the planner assumes every index narrows the search to a handful of rows, which is fine when the schema has one obvious index per query. It matters when a query could use two different indexes, or when an indexed column has few distinct values (a status flag), because only the statistics tell the planner which choice reads fewer rows. Run ANALYZE after the data reaches a realistic size, or call PRAGMA optimize when connections close."},{"question":"Why is LIKE '%text%' so slow?","answer":"A B-tree index is ordered left to right, so a pattern starting with a wildcard can only be scanned, not sought. A prefix match (LIKE 'abc%') can seek, but only with an index declared COLLATE NOCASE or with GLOB 'abc*' against a normal index. For words anywhere in the text, use an FTS5 full-text table; for suffix search, store the reversed string and index that."},{"question":"Can I index a function like lower(email)?","answer":"Yes. SQLite supports indexes on expressions: CREATE INDEX idx ON users(lower(email)) makes WHERE lower(email) = ? a SEARCH. The expression in the index must match the query exactly."},{"question":"Is PRAGMA cache_size worth tuning?","answer":"Occasionally. The default page cache is small (-2000, meaning about 2 MB, in standard builds; run PRAGMA cache_size to see yours), and it is per connection, so an app whose working set is larger pays repeated reads through the OS. Set it per connection with a negative number of KiB, for example PRAGMA cache_size = -65536 for 64 MB. Raising it to tens of megabytes is cheap on desktop hardware; on memory-tight mobile targets, measure before raising."},{"question":"How do I inspect the plan outside the app?","answer":"EXPLAIN QUERY PLAN is plain SQL and works from any client, including the sqlly CLI and the desktop app's query editor. You can also paste the plan text into SQLly's free query plan viewer at /tools/query-plan-viewer."}],"plan_group":null,"related_slugs":[]},"source_url":"https://sqlly.app/sql-performance/sqlite","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/sudden-slowdown","corpus":"sql-performance","engine":null,"language":"en","title":"When a fast query turns slow","description":"A fast SQL query turned slow overnight: the likely causes (statistics, plan changes, data growth, locks, vacuum) and how to prove which one it is.","body":{"slug":"sudden-slowdown","engines":["SQL Server","PostgreSQL","MySQL","SQLite","Oracle"],"symptoms":["Sudden slowdown","Bad index usage"],"h1":"When a fast query turns slow","lede":"The query has not changed but it now takes seconds. What actually changed: statistics, the chosen plan, the data size, the indexes, or what it waits behind. How to find out which, per engine.","symptom_html":"<p>Fast yesterday, slow today, same SQL. The query is not the variable - its environment is. There are only a handful of things that change under a running system, and each leaves evidence.</p>","diagnosis_html":"<h3>First: is it slow, or is it waiting?</h3>\n<p>Catch the query while it runs. On SQL Server, <code>sys.dm_exec_requests</code> shows <code>blocking_session_id</code> and wait type; on PostgreSQL, <code>pg_stat_activity</code> shows <code>wait_event_type = 'Lock'</code>; on MySQL, <code>sys.innodb_lock_waits</code>; on Oracle, <code>v$session.blocking_session</code>. If it is waiting behind another session, this is a blocking problem and the <a href=\"/sql-performance/blocking-deadlocks\">blocking guide</a> is the one to read.</p>\n<h3>SQL Server: find the plan change</h3>\n<p>The most common cause on SQL Server: the optimizer picked a different plan. Query Store keeps every plan, so the flip is visible directly - one <code>query_id</code> whose times got worse when the <code>plan_id</code> changed:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>SELECT p.plan_id, p.last_compile_start_time,\nrs.avg_duration / 1000.0 AS avg_ms, rs.count_executions\nFROM sys.query_store_query AS q\nJOIN sys.query_store_plan AS p ON p.query_id = q.query_id\nJOIN sys.query_store_runtime_stats AS rs ON rs.plan_id = p.plan_id\nWHERE q.query_id = 123\nORDER BY rs.start_time;</code></pre>\n<p>A new <code>plan_id</code> appearing partway through the history, with worse durations after it, is the regression. The Regressed Queries report in SSMS shows the same thing, and <code>sp_query_store_force_plan</code> pins the good plan back while you investigate (the fix section has the statement). On PostgreSQL and MySQL, compare today's <code>EXPLAIN ANALYZE</code> with one from before the change, if you saved one - PostgreSQL's <code>auto_explain</code> module logs the plans of slow statements automatically, which is worth leaving on for exactly this reason. Read each in the <a href=\"/tools/query-plan-viewer\">query plan viewer</a>. A plan flip with identical SQL and parameters points at statistics.</p>\n<h3>PostgreSQL: check the statistics age</h3>\n<p>A bulk load, a big delete, or a migration changed the data shape; the next stats refresh recompiles and picks a different plan. The tell is in the plan: estimated rows that no longer match actual rows on the same node. Each engine records when its statistics were last rebuilt, so start there:</p>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>SELECT relname, last_analyze, last_autoanalyze,\nn_mod_since_analyze, n_live_tup\nFROM pg_stat_user_tables\nWHERE relname = 'orders';</code></pre>\n<p><code>n_mod_since_analyze</code> (PostgreSQL 13 and later) counts rows changed since the last analyze. A large number next to an old <code>last_autoanalyze</code> means the planner is choosing from measurements taken before the data changed.</p>\n<h3>MySQL: check the statistics date</h3>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>SELECT table_name, last_update, n_rows\nFROM mysql.innodb_table_stats\nWHERE database_name = DATABASE() AND table_name = 'orders';</code></pre>\n<p><code>last_update</code> is when InnoDB last (re)gathered the statistics, not when the data last changed. Reading the table needs SELECT on the mysql schema, which application accounts usually lack. Compare the date with when the slowdown started.</p>\n<h3>SQLite: check the numbers the planner has</h3>\n<p>SQLite keeps no statistics history; <code>sqlite_stat1</code> is what the planner reads, and it is only as fresh as the last <code>ANALYZE</code>:</p>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>SELECT * FROM sqlite_stat1 WHERE tbl = 'orders';\nEXPLAIN QUERY PLAN SELECT * FROM orders WHERE customer_id = 42;</code></pre>\n<p>An empty <code>sqlite_stat1</code> (or no such table yet, before the first ANALYZE) means every plan decision rests on default guesses.</p>\n<h3>Oracle: check the statistics date and the plan hash</h3>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>SELECT table_name, last_analyzed, num_rows\nFROM user_tables\nWHERE table_name = 'ORDERS';\n\nSELECT sql_id, plan_hash_value, child_number, last_active_time\nFROM v$sql\nWHERE sql_text LIKE 'SELECT%ORDERS%'\nAND sql_text NOT LIKE 'SELECT sql_id%'\nORDER BY child_number;</code></pre>\n<p><code>user_tab_modifications</code> adds the other half: the inserts, updates and deletes recorded since the last gather. Two different <code>plan_hash_value</code> values under one <code>sql_id</code> is the plan change, or read the old and new plans with <code>DBMS_XPLAN.DISPLAY_CURSOR</code> per child cursor, or <code>DBMS_XPLAN.DISPLAY_AWR</code> with the Diagnostics Pack.</p>\n<h3>The data crossed a threshold</h3>\n<p>A table grew past the point where the old plan was cheapest - a nested loop over 500 rows is fine, over 5 million it is not. Nothing regressed; the query outgrew its plan. The fix is the index the new plan needs, not a complaint about the optimizer.</p>\n<h3>Something else in the system changed</h3>\n<p>An index was dropped by a migration, autovacuum fell behind on Postgres (<code>n_dead_tup</code> ballooning in <code>pg_stat_user_tables</code>), a config change shrank a cache, or the disk filled up. On SQLite, which has no plan cache to regress, growth past a few hundred thousand rows plus a missing index is the overwhelming favorite - check <code>EXPLAIN QUERY PLAN</code> for a SCAN that used to be cheap when the table was small.</p>","fix_html":"<p>Work in this order: prove it is not waiting (step 1), compare the current plan with the last known-good plan, refresh the statistics and re-measure, then fix the access path if the plan is now honest and still slow. If you cannot reproduce it, leave instrumentation in place - slow query log, Query Store, pg_stat_statements - because the next occurrence will leave the evidence the first one did not.</p>\n<h3>Refresh the statistics, then re-measure</h3>\n<p>One statement per engine. Run it outside peak hours on the big tables, because a full gather is itself a load on the server:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>UPDATE STATISTICS dbo.Orders WITH FULLSCAN;</code></pre>\n<pre class=\"perf-code\" data-engine=\"postgresql\"><code>ANALYZE orders;</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>ANALYZE TABLE orders;</code></pre>\n<pre class=\"perf-code\" data-engine=\"sqlite\"><code>ANALYZE;</code></pre>\n<pre class=\"perf-code\" data-engine=\"oracle\"><code>EXEC DBMS_STATS.GATHER_TABLE_STATS(USER, 'ORDERS');</code></pre>\n<p>On SQL Server, when the statistics were fine and the plan genuinely flipped, force the last known-good plan back while you investigate the cause:</p>\n<pre class=\"perf-code\" data-engine=\"sql-server\"><code>EXEC sp_query_store_force_plan @query_id = 123, @plan_id = 456;\n-- undo it once the real fix is in place:\nEXEC sp_query_store_unforce_plan @query_id = 123, @plan_id = 456;</code></pre>\n<p>Do not force a plan and walk away - it will outlive the data change that made it right. When the fix lands, unforce it.</p>\n<h3>When it is not the plan</h3>\n<p>A slowdown that follows a daily pattern is not a plan problem: backups, batch jobs and traffic peaks contend for the same CPU, disk and locks, and the <a href=\"/sql-performance/high-cpu\">high CPU</a> and <a href=\"/sql-performance/blocking-deadlocks\">blocking</a> guides are the ones to read. The first run after a restart is slower because the caches are cold - measure again before concluding anything. And when the data has simply grown past the point where the old plan was cheapest, the answer is the index the new size needs; forcing yesterday's plan onto twice the rows makes things worse.</p>\n<p>Resist restarting the server as a fix. A restart clears the plan cache and the buffer pool, which can mask a statistics problem for a day and resets the evidence you need.</p>","checklist_html":["Catch the query running and check whether it is working or waiting on locks.","Compare the current execution plan with the last known-good one.","If the plan flipped with the same inputs, refresh statistics and re-measure.","Check table row counts against last week; growth past a threshold changes the cheapest plan.","Verify no migration dropped or changed an index the query uses.","On PostgreSQL, check n_dead_tup and last_autovacuum in pg_stat_user_tables.","Leave the slow log / Query Store / pg_stat_statements on so the next occurrence is captured."],"faqs":[{"question":"Nothing changed in the database - how can the plan change?","answer":"Statistics age on their own schedule, the data grows with normal use, and autovacuum or auto-update-stats runs in the background. A plan is a function of the data's shape as the optimizer last measured it, so 'nothing changed' almost always means 'the measurement changed'."},{"question":"How do I pin a good plan while I investigate?","answer":"SQL Server: sp_query_store_force_plan; Query Store hints, which add a hint without editing the statement text, arrived separately in SQL Server 2022. Oracle: a SQL Plan Baseline loaded from the cursor cache with DBMS_SPM. PostgreSQL has no built-in plan pinning; the pg_hint_plan extension adds hints, otherwise fix the statistics or add the index that makes the good plan the obvious choice. MySQL has no plan baselines either, only optimizer hints written into the statement itself. In every case the pinned plan is a tourniquet, not a treatment."},{"question":"Could an application deploy make the query slow without touching the SQL?","answer":"Yes: a new ORM version may change parameter types (an implicit conversion that blocks an index), wrap the query differently, or fetch more columns. Capture the exact SQL the app sends now - from the engine's statement history - and compare it with what you profiled before."},{"question":"The slowdown follows a daily pattern - afternoon only. Still a plan change?","answer":"Usually not. A time-of-day pattern points at contention: backups, batch jobs, traffic peaks saturating CPU or I/O, or lock queues behind a scheduled writer. See the high CPU and blocking guides; the sudden-slowdown question is for when it never recovers."},{"question":"Where do I compare the old and new plans?","answer":"Save both. The free query plan viewer at /tools/query-plan-viewer renders one plan at a time, so open each in its own tab and compare the expensive operators. The SQLly desktop app keeps a history of plans per query tab and diffs any two of them operator by operator."}],"plan_group":null,"related_slugs":[]},"source_url":"https://sqlly.app/sql-performance/sudden-slowdown","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-performance/using-temporary","corpus":"sql-performance","engine":null,"language":"en","title":"Using temporary in MySQL plans","description":"Using temporary in EXPLAIN means MySQL builds a hidden table to group, de-duplicate or sort. When that is slow and how an index or a setting removes it.","body":{"slug":"using-temporary","engines":["MySQL"],"symptoms":["Slow query","Memory pressure"],"h1":"Using temporary in MySQL plans","lede":"MySQL builds an internal temporary table when it cannot group, de-duplicate or order rows as it reads them. How to see it in EXPLAIN, tell whether the table went to disk, and remove it with an index.","symptom_html":"<p><code>Using temporary</code> in the <code>Extra</code> column of <code>EXPLAIN</code> means MySQL will build an internal temporary table to answer the query. It does that for <code>GROUP BY</code> and <code>DISTINCT</code> when the rows do not arrive already grouped, for <code>UNION</code>, for some derived tables, and for an <code>ORDER BY</code> on columns of a table other than the first one joined. Together with <code>Using filesort</code> it means the temporary table is also sorted afterwards.</p>\n<p>A small temporary table in memory costs little. It gets expensive when it holds many rows or outgrows its memory limit and moves to disk. The <a href=\"/tools/query-plan-viewer\">query plan viewer</a> points out temporary tables in MySQL and MariaDB plans. The examples use a shop schema with 400,000 orders.</p>","diagnosis_html":"<h3>Find the temporary table in the plan</h3>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN SELECT status, COUNT(*) FROM orders GROUP BY status\\G</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code> type: ALL\n  key: NULL\n rows: 399054\nExtra: Using temporary</code></pre>\n<p>The tree format says what the table is for:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>EXPLAIN FORMAT=TREE SELECT status, COUNT(*) FROM orders GROUP BY status;\n\nEXPLAIN FORMAT=TREE SELECT DISTINCT customer_id FROM orders;</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>-&gt; Table scan on &lt;temporary&gt;\n    -&gt; Aggregate using temporary table\n        -&gt; Table scan on orders  (cost=40266 rows=399054)\n-&gt; Table scan on &lt;temporary&gt;  (cost=80172..85162 rows=399054)\n    -&gt; Temporary table with deduplication  (cost=80172..80172 rows=399054)\n        -&gt; Table scan on orders  (cost=40266 rows=399054)</code></pre>\n<p><code>Aggregate using temporary table</code> keeps one row per group and updates it as rows are read. <code>Temporary table with deduplication</code> keeps one row per distinct value. In both, the size of the temporary table is the number of groups, not the number of rows read.</p>\n<h3>Check whether it went to disk</h3>\n<p>Two session counters tell you: <code>Created_tmp_tables</code> counts internal temporary tables, <code>Created_tmp_disk_tables</code> counts the ones that were moved to disk. This query has 400,000 groups:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>SET SESSION tmp_table_size = 16 * 1024 * 1024;\nFLUSH STATUS;\n\nSELECT reference, COUNT(*) FROM orders\nGROUP BY reference ORDER BY COUNT(*) DESC LIMIT 1;\n\nSHOW SESSION STATUS LIKE 'Created_tmp%tables';</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>| Created_tmp_disk_tables | 1     |\n| Created_tmp_tables      | 1     |</code></pre>\n<p>The same counters with <code>SHOW GLOBAL STATUS</code> give the ratio for the whole server since it started.</p>","fix_html":"<h3>Add an index on the grouping columns</h3>\n<p>If an index stores the rows in <code>GROUP BY</code> order, MySQL reads the index and finishes each group as it passes; no temporary table is needed:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>CREATE INDEX orders_status_idx ON orders (status);\n\nEXPLAIN SELECT status, COUNT(*) FROM orders GROUP BY status\\G</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code> type: index\n  key: orders_status_idx\n rows: 399054\nExtra: Using index</code></pre>\n<p>When the query also filters, put the equality filter columns first and the grouping columns after them, the same rule as for an <a href=\"/sql-performance/expensive-sort\">index that avoids a sort</a>.</p>\n<h3>Group and order by columns of one table</h3>\n<p>In a join, <code>ORDER BY</code> or <code>GROUP BY</code> on a column of a table that is not read first forces MySQL to collect the joined rows in a temporary table before it can order them. If the same result can be grouped by a column of the driving table (for example its key instead of a column from the joined table), the temporary table goes away. Check the join order in <code>EXPLAIN</code>: the first row is the table read first.</p>\n<h3>Reduce what goes into the table</h3>\n<p>Filter before grouping, and keep wide columns out of the grouped result. Fetch long text columns in an outer query that joins back on the key after the grouping is done.</p>\n<h3>Raise the in-memory limit for the session</h3>\n<p>When the temporary table is legitimate but spills to disk, give it more memory for that session:</p>\n<pre class=\"perf-code\" data-engine=\"mysql\"><code>SET SESSION tmp_table_size = 256 * 1024 * 1024;\nFLUSH STATUS;\n\nSELECT reference, COUNT(*) FROM orders\nGROUP BY reference ORDER BY COUNT(*) DESC LIMIT 1;\n\nSHOW SESSION STATUS LIKE 'Created_tmp%tables';</code></pre>\n<pre class=\"perf-code\" data-engine=\"mysql\" data-role=\"output\"><code>| Created_tmp_disk_tables | 0     |\n| Created_tmp_tables      | 1     |</code></pre>\n<p>The settings involved are <a href=\"/sql-configuration/mysql/tmp-table-size\">tmp_table_size</a>, the per-table limit, and <a href=\"/sql-configuration/mysql/temptable-max-ram\">temptable_max_ram</a>, the total for all sessions. <a href=\"/sql-configuration/mysql/max-heap-table-size\">max_heap_table_size</a> also applies when the server uses the MEMORY engine for internal tables.</p>\n<h3>When to leave it alone</h3>\n<p>Leave it when the number of groups is small: a temporary table with five rows, one per status, is not what makes a query slow, even if reading 400,000 rows to fill it is. In that case the scan is the cost, and the fix is a filter or a <a href=\"/sql-performance/full-table-scan\">better access path</a>. <code>UNION</code> without <code>ALL</code> always uses a temporary table to remove duplicates; use <code>UNION ALL</code> when duplicates are impossible or acceptable.</p>","checklist_html":["Find Using temporary in the Extra column and identify what needs it: GROUP BY, DISTINCT, UNION or ORDER BY.","Estimate the number of groups or distinct values, which is the size of the temporary table.","Check Created_tmp_disk_tables to see whether it went to disk.","Try an index on the filter columns followed by the grouping columns.","In joins, group and order by columns of the first table read.","Raise tmp_table_size for the session only when the table is needed and too big for memory."],"faqs":[{"question":"What does Using temporary mean in MySQL EXPLAIN?","answer":"MySQL will create an internal temporary table to hold intermediate results, most often for GROUP BY, DISTINCT or UNION, or to sort a join result. The table is created and dropped automatically within the query."},{"question":"Is Using temporary always bad?","answer":"No. The cost depends on how many rows the temporary table holds and whether it fits in memory. A handful of groups is cheap. Hundreds of thousands of groups, or a table that moves to disk, is where the time goes."},{"question":"What does Using temporary; Using filesort mean?","answer":"The query builds a temporary table and then sorts it. It is typical of GROUP BY followed by ORDER BY on an aggregate, such as ordering groups by their count, and of ordering a join by a column that does not come from the first table."},{"question":"How do I know if a temporary table went to disk?","answer":"Compare the status counters Created_tmp_disk_tables and Created_tmp_tables before and after the query in your session. If the disk counter increased, the table exceeded its memory limit and was converted to an on-disk table."},{"question":"Does UNION use a temporary table?","answer":"UNION does, because it has to remove duplicate rows. UNION ALL returns rows as they come and in most cases needs no temporary table, so prefer it whenever duplicates cannot occur or do not matter."}],"plan_group":"Sorts, memory and temp space","related_slugs":["expensive-sort","sort-and-hash-spills","mysql"]},"source_url":"https://sqlly.app/sql-performance/using-temporary","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
