The symptom
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.
das query plan viewer labels every step of a plan with one of the kinds below. If you have not read a plan before, start with how to read an execution plan. The two examples use a shop schema with 20,000 customers and 400,000 orders.
Diagnose it
Scan
Reads a whole table or a whole index, row after row, and keeps the rows that pass the filter. Names: Table Scan, Clustered Index Scan und Index Scan in SQL Server; Seq Scan in PostgreSQL; Table scan und Index scan in MySQL (ALL und index in the tabular format); TABLE ACCESS FULL und INDEX FULL SCAN in Oracle; SCAN in SQLite deklariert wird.
EXPLAIN SELECT * FROM customers WHERE country = 'DE';
Seq Scan on customers (cost=0.00..417.00 rows=4000 width=36)
Filter: (country = 'DE'::bpchar)
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 full table scan.
Seek
Goes through an index to the rows that match a condition and reads only those. Names: Index Seek und Clustered Index Seek in SQL Server; Index Scan, Index Only Scan und Bitmap Index Scan in PostgreSQL; Index lookup, Single-row index lookup und Index range scan in MySQL (ref, eq_ref, const und range in the tabular format); INDEX UNIQUE SCAN und INDEX RANGE SCAN in Oracle; SEARCH in SQLite deklariert wird.
EXPLAIN SELECT * FROM orders WHERE order_id = 42;
Index Scan using orders_pkey on orders (cost=0.42..8.44 rows=1 width=37)
Index Cond: (order_id = 42)
The name is a trap in PostgreSQL: an Index Scan there is usually a seek, and the Index Cond 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 index not used und non-sargable predicates.
Lookup
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: Key Lookup und RID Lookup in SQL Server; Bitmap Heap Scan in PostgreSQL, where a plain Index Scan also includes the table fetch; TABLE ACCESS BY INDEX ROWID 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.
A lookup costs one table visit per row. A few hundred are free, a few hundred thousand are not; see key lookups and, for PostgreSQL, index-only scans and heap fetches.
Nested loop join
For each row of the outer input, finds the matching rows in the inner input. Names: Nested Loops in SQL Server and Oracle, Nested Loop in PostgreSQL, Nested loop inner join in MySQL. SQLite joins this way and shows it as one line per table, in loop order.
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. Join algorithms covers how to tell.
Hash join
Reads one input into an in-memory hash table, then reads the other and probes the table for matches. Names: Hash Match in SQL Server, Hash Join in PostgreSQL, Inner hash join in MySQL, HASH JOIN 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 sort and hash spills.
Merge join
Walks two inputs that are sorted on the join columns and matches them in one pass. Names: Merge Join in SQL Server and PostgreSQL, MERGE JOIN 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.
Other joins and cross products
Joins whose method is chosen at run time, such as SQL Server's Adaptive Join, and joins with no join condition, such as Oracle's MERGE JOIN CARTESIAN. A cross product pairs every row of one input with every row of the other. Unless you wrote CROSS JOIN on purpose, look for a missing join condition; see join row explosion.
Sortieren
Puts rows in order for ORDER BY, and for operators above it that need sorted input. Names: Sort in SQL Server, PostgreSQL and MySQL (Using filesort in MySQL's tabular format); SORT ORDER BY in Oracle; USE TEMP B-TREE FOR ORDER BY 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 expensive sorts.
Aggregation
Computes GROUP BY, DISTINCT and aggregate functions such as count und sum. There are two methods. A hash aggregate (Hash Match (Aggregate), HashAggregate, HASH GROUP BY) builds one entry per group in memory. A stream aggregate (Stream Aggregate, GroupAggregate, SORT GROUP BY) reads input already sorted by the grouping columns. MySQL prints Aggregate using temporary table oder Group aggregate, and SQLite USE TEMP B-TREE FOR GROUP BY. Siehe Using temporary for the MySQL case.
Fenster
Computes window functions: anything with OVER (...). Names: Sequence Project, Window Spool und Window Aggregate in SQL Server; WindowAgg in PostgreSQL; Window aggregate in MySQL; WINDOW SORT und WINDOW BUFFER in Oracle. The window operator is usually cheap. The sort beneath it, on the PARTITION BY und ORDER BY columns, is usually not.
Spool and materialize
Saves rows so the plan can read them again without recomputing them. Names: Table Spool, Index Spool und Row Count Spool in SQL Server; Materialize, Memoize und Hash (the build step of a hash join) in PostgreSQL; Materialize und Temporary table in MySQL; TEMP TABLE TRANSFORMATION und BUFFER SORT in Oracle; MATERIALIZE in SQLite. A spool that builds an index is the engine making the index it could not find; see index spools and automatic indexes. For a CTE that is computed in full before it is filtered, see CTE materialization.
Parallelism
Moves rows between the threads or processes of a parallel plan. Names: Parallelism mit Gather Streams, Distribute Streams oder Repartition Streams in SQL Server; Gather und Gather Merge in PostgreSQL; the PX steps in Oracle. Everything beneath one runs in several workers at once. Parallel query plans covers workers that never started and rows that all landed on one thread.
Filtern
Discards rows that fail a condition which no operator beneath it could apply. Names: Filter in SQL Server, MySQL and Oracle. PostgreSQL shows it as a Filter line on another step, with Rows Removed by Filter 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.
Compute
Evaluates expressions for each row. Names: Compute Scalar und Segment 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 scalar functions.
Modify
Writes: INSERT, UPDATE, DELETE und MERGE. Names: Clustered Index Insert, Table Update and their relatives in SQL Server; Insert, Update und Delete 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.
Remote
Work done on another server. Names: Remote Query und Remote Scan in SQL Server (linked servers), Foreign Scan in PostgreSQL (foreign data wrappers), REMOTE 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.
Set operations
Combines the results of several inputs: UNION, UNION ALL, INTERSECT und EXCEPT, and reading the partitions of a partitioned table. Names: Concatenation in SQL Server, Append und Merge Append in PostgreSQL, UNION-ALL in Oracle, COMPOUND QUERY in SQLite deklariert wird. UNION ohne ALL adds a sort or hash to remove duplicates. For an Append over more partitions than the query needs, see partition pruning.
Limit
Stops after a number of rows. Names: Top in SQL Server, Limit in PostgreSQL and MySQL, COUNT STOPKEY 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 row goals.
Subquery
A subquery, CTE, derived table or view that is evaluated as a unit. Names: Subquery Scan und CTE Scan in PostgreSQL; Materialize CTE und die DEPENDENT SUBQUERY select type in MySQL; VIEW in Oracle; CO-ROUTINE, SCALAR SUBQUERY und CORRELATED SCALAR SUBQUERY in SQLite. SQL Server has no such operator; it turns subqueries into joins. What matters is how many times the unit runs. See correlated subqueries.
Table function
Rows produced by a function: a table-valued function, generate_series, unnest, a JSON table. Names: Table Valued Function in SQL Server, Function Scan in PostgreSQL, COLLECTION ITERATOR 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 row estimates that are far off.
Konstant
Rows that come from the query text and not from a table: a VALUES list, a SELECT ohne FROM. Names: Constant Scan in SQL Server, Result und Values Scan in PostgreSQL, FAST DUAL in Oracle. Nothing to tune.
Ergebnis
The root of the plan, which returns rows to the client. Oracle prints it as SELECT STATEMENT and SQLite as QUERY PLAN. Its cost and time are the totals for the statement.
Lock
Locks the rows a query selected, for SELECT ... FOR UPDATE. Names: LockRows in PostgreSQL, FOR UPDATE in Oracle. If this step is slow the query is waiting for another session; see blocking and deadlocks.
Andere
Steps that fit none of the above, such as Oracle's PARTITION RANGE steps, which choose the partitions to read, and SQL Server's cursor operators. They rarely cost anything themselves. Read the steps beneath them.
Fix it
Judge an operator by its numbers
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.
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.
When to leave it alone
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.
The checklist
Work through it in order. Each step gives you the evidence for the next one.
- 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.
Questions that come up
What is the difference between an index scan and an index seek?
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.
Is a table scan always bad?
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.
What is a Hash Match in SQL Server?
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.
What does Bitmap Heap Scan mean in PostgreSQL?
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.
What does SEARCH mean in a SQLite query plan?
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.