Optimizer
optimizer
Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.
Predicate pushdown (through projections, into join sides, outer-join safe;
a condition with a correlated subquery stays above a semi or anti join,
which only drops rows — an uncorrelated one runs once and goes below; an
OR across both sides of an inner join pushes down to each the OR of its
branches’ conjuncts on it, when every branch has one, the OR itself
kept; a scan’s filter holds each conjunct once), WHERE conjuncts into join conditions — the conjuncts every
branch of an OR has taken out of it first ((a AND b) OR (a AND c) is
a AND (b OR c); not volatile calls or subqueries), so a join condition
repeated in each branch joins —, hash joins on equality conjuncts,
access paths: primary key or index with an equality prefix and a range on
the next column; the filter always stays, so an access path only narrows.
A condition whose correlated subquery reads this row’s columns goes only
where they all are, and moving it (a join side, a reordered join, through
a projection) rewrites the subquery’s references with it. A scan
filter’s comparisons with constant expressions compare with their values,
computed when the plan is made (o_orderdate < DATE '1993-07-01' + INTERVAL '3' MONTH with 1993-10-01 00:00:00; not volatile calls,
parameters or subqueries): estimated from the histogram, checked against
a segment’s least and greatest, and not computed per row.
Unnesting (unnest): a WHERE or scan-filter conjunct EXISTS (…),
NOT EXISTS (…) or x IN (…) becomes a semi or anti join with the
subquery’s rows — one pass over each, hashed on the correlation’s
equalities — when the subquery’s rows do not depend on the row
(uncorrelated IN), or when it reads one table or a CTE’s rows (under
projections, DISTINCT, sorts) and refers to the row only in its
filter’s top-level conjuncts, which become the join condition — a CTE’s
rows are made once a statement however often they are read, so the join
never costs more than the subquery run per row (EXISTS (SELECT 1 FROM d WHERE d.id = t.id) over a walk’s rows and 200,000 rows: 2.4 s → 1.4 ms);
not a derived table’s, whose run per row may look its tables up. The right side keeps only
the columns the condition reads. Once the inner joins are ordered, each
semi and anti join moves down among them, as far as the columns it reads
allow and while the rows it meets there are no more (a subquery filtering
one table filters it before the joins that multiply it, after those that
narrow it; without statistics, as deep as it goes). A comparison with a
scalar subquery aggregating one table’s rows that match the row — TPC-H
Q20’s ps_availqty > (SELECT 0.5 * sum(l_quantity) FROM lineitem WHERE l_partkey = ps_partkey AND l_suppkey = ps_suppkey …) — becomes, after
the semi and anti joins, an inner join of the rows with the table’s on
those equalities, grouped by the row’s columns, the comparison on each
group’s value (Galindo-Legaria and Joshi’s Apply removal; Neumann and
Kemper’s unnesting): when the row’s columns compared are its own key (a
primary key, through filters, projections, semi and anti joins:
eager::unique), the aggregates give NULL over no rows (sum, avg,
min, max — not count) and the value stays NULL with them
(arithmetic; division by a constant other than zero), so a row nothing
matches, which has no group, is dropped as its NULL comparison would
drop it. Otherwise the subquery stays, its results kept by the values
it reads (TPC-H Q17’s, whose part repeats over its lines).
Narrow rows (narrow, last): the columns nothing above a join reads
are cut from its inputs by projections, every reference above moved with
them, so a join copies only what is used.
The output after the limit (postponed, last; §M14.21 T8b): under
LIMIT, a projection below the sort has its expressions the sort does
not order by — not columns or constants — computed above the limit
instead, the sort carrying the columns they read (PostgreSQL’s
make_sort_input_target, which does it for expensive or volatile ones
only): SELECT id, ts_headline(…) … ORDER BY ts_rank(…) DESC LIMIT 10
computes ten headlines, not one a match, and a value of a row the limit
drops is never computed (nor its error raised). A projection right
above the limit takes the expressions in.
Index nested loops (lookups): a hash join whose right side is an
analyzed table’s scan becomes an index nested loop when an index (the
primary key or a secondary one) leads with the join keys and the lookups
cost less than hashing the table — each lookup counted as 55 rows of a
scan, each row a secondary index finds 60 more (its fetch; measured on
TPC-H, §M14.12 V3, the lookup again in §M14.33 R4), against the table’s rows read once; a column table’s
lookups count 1.2 times as much and its rows scanned a quarter (its
scans read batches of the columns wanted, its lookups segments’ values);
the rows a lookup reads are all of its key value’s, whatever the filter
keeps — a semi or anti join’s stop at the first match. An inner join
may look up its left side instead (the columns put back in order above),
and so may a semi join whose right side has each key once (its columns
the primary key of the one table it reads, eager::unique): an inner
join then, each left row matching one right row at most, the left’s
columns kept (PostgreSQL turns such a semi join into an inner one, its
inner side unique). TPC-H Q20’s subquery looks partsupp up by its
parts.
A lookup join’s rows are estimated as the left side’s times a lookup’s.
Its condition drops its key equalities (optimizer::without_keys): the
right side’s scan holds them in its filter, applied by its range or
checked on each row where the range cannot apply them (Access::rest),
so a join wanting no other column of the right rows reads none — a count
of matches by a secondary index reads its entries alone, no row fetched
(as PostgreSQL’s index-only scan). A scan by a secondary index wanting
only columns its entries hold — the primary key’s, and the index’s own
held by their values (not an expression’s, nor in a taught ordering) —
reads them from the entries too, where their key encoding gives them
back as they were: integers, booleans, text, bytes, dates and times, not
a real, a numeric’s scale, a char’s padding or an enum’s label
(exec::FromEntries; no visibility map needed: the entries are
versioned as the rows are). An adaptive join’s
lookups want the left columns read above the join and by their own
condition, not its hash keys (prune).
Adaptive joins (adaptive, last, after narrowing): an inner hash
join whose left side such an index could look up keeps that plan beside
the hash join’s (plan::Adaptive; EXPLAIN: Hash Join (…) or lookups up to N rows), N the right rows below which the lookups cost less.
The join makes its right side first, as a hash join does (on the workers,
gathered, or stashed); with at most N rows they look the left side’s
table up, each right row outside (an index nested loop, its rows put
back left columns first), the left side never scanned; with more, the
hash join runs. A right side estimated larger than it is — TPC-H Q18’s
HAVING sum(l_quantity) > 300, a third of the orders by estimate, 57 in
fact — then costs what the right estimate would have (Oracle 12c’s
adaptive plans, SQL Server 2017’s adaptive joins). The rows are the hash
join’s, in the right rows’ order; the choice is the same in every
executor (vector::prepare makes it for a pipeline, exec‘s join
otherwise). Not where the left side reads an enclosing row.
A recursive query’s step joining its last round to a table is made one
(PLAN.md §M14.34 G1): lookups leaves the hash join whose right side
reads the round (binder::reads_work_table) rather than looking the
table up for a round estimated at a constant, so each round chooses —
few rows look the table up, many hash the round and scan the table
once — and a round’s rows, at hand (exec::is_round), are counted
before a table is made of them. A 2,000,000-row tree walked whole:
3.0 s → 0.68 s (PostgreSQL 18’s index nested loop: 1.30 s); its small
walks still by lookups, as fast as before. A join reading a recursive
query’s rows is one too, for the same reason (optimizer::rows_unknown:
the estimate a guess) — the walk’s 2,000,000 rows joined to the table by
its key hashed, not looked up 2,000,000 times (2.4 → 0.74 s; PostgreSQL
2.5 s) —, and a semi join over them (IN, EXISTS) where nothing past
its keys tells their rows apart: each distinct key looked up once, a
left row given once (2,047 rows’ IN 20 → 7 ms). Other semi joins keep
their estimated plans: TPC-H Q18’s, made lookups, left the join above it
without its pipeline (146 → 164 ms on column tables).
Parallel aggregates in key order: grouped by (at least) the leading
column of the primary key a scan reads in order, the morsels’ groups meet
only at their edges — the groups of a morsel’s first and last prefix —
so each morsel finishes the others itself, on its worker, and hands over
only its edges’ partial states, merged in the morsel order (TPC-H Q18’s
GROUP BY l_orderkey, 1.5 million groups: 600 → 240 ms). A million
groups do not have to fit in work_mem at once (they would, merging into
one table, and the run fell back to one thread partitioning); a group
that fails to finish is the one a single pass finishes first.
Eager aggregation (eager; Yan & Larson): a grouping by a join’s
left key — the key of the left side’s single table, its primary key —
whose aggregates read only right columns and cannot fail
(Aggregate::infallible: count, min, max, bool_and, bool_or)
is computed on the right side first, by its join key, and then joined:
c LEFT JOIN o … GROUP BY c.id becomes c LEFT JOIN (SELECT cid, count(…) FROM o GROUP BY cid), a group a customer through the join
rather than a row an order (TPC-H Q13, 367 → 111 ms on column tables).
A left row no right row matches gets what its aggregate gives for the
padded row (count(x) 0, count(*) 1, min(x) NULL). It holds when
the join is inner or left on key equalities only, the right side has at
most half as many groups as rows, and the join keeps at least half of
them (else its key filter narrows the right side more cheaply than a
grouping of all of it); an inner join is tried both ways round, and
through a projection of columns. Not for a unique index (its NULLs
repeat) or an aggregate that can fail (the right rows no left row
matches are aggregated too, and their error would come where the join
gave none).
DISTINCT over a key left out (distinct::needless): a call’s
DISTINCT over a column that is its table’s primary key of one column,
read by a scan through filters, sorts, limits and projections (no join,
which repeats rows), is dropped — the values are distinct already (as
SQL Server simplifies COUNT(DISTINCT key)); not over a real or
double precision key. The statistics suite’s count(DISTINCT id) on
ten million rows 806 → 90 ms.
DISTINCT inside aggregates as groupings (distinct, §M14.20 W6):
SELECT g, count(DISTINCT x), sum(y) … GROUP BY g is aggregated twice —
by g, x, the other aggregates giving their partial states
(partial sum(y) in EXPLAIN), then by g, the DISTINCT one fed
each x once and the others combining the partial states (combined sum) — so both are the vectorized, parallel grouping within
work_mem, where a DISTINCT call kept a set of values a group, a row
at a time on one thread (ClickBench Q4, count(DISTINCT UserID), 558 →
15 ms). It holds when the DISTINCT calls share their arguments, no
call has an ORDER BY, every aggregate’s result is the same in any
order of its rows (Aggregate::order_free: not array_agg or
string_agg), the others have partial states and the input is a
pipeline (a scan through filters and projections — over a join’s rows,
a row at a time, the two groupings would only hash each row twice:
TPC-H Q16 127 → 192 ms); the result is the set’s, NULLs and errors
included. Over hash joins the pipeline probes — known only when it
runs, its tables built — the executor groups twice itself when every
call is DISTINCT over the same arguments and order-free
(vector::distinct_aggregate: the distinct rows by the vectorized,
parallel grouping, then a batch at a time by the group; TPC-H Q16 on
ten workers 100.7 → 80.2 ms). NOT IN stays a subquery (its NULL
semantics are not an anti join’s); so do correlated scalar subqueries.
EXPLAIN prints the plan (columns as #n); EXPLAIN ANALYZE runs it
too (§8.13).