Referencia · §8.5

Plans and the executor

plan, exec, expr

Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.

Plan nodes: Scan (table, access path, filter), Values, Filter, Project, Join (inner, left, full; nested loop or hash), Aggregate, Sort, Limit, Distinct, SetOp (union, except, intersect), Cte (computed once per execution, shared by its references), Recursive / WorkTable (WITH RECURSIVE: the step re-runs over the previous round until it yields nothing; UNION drops repeats, so cycles end; USING KEY keeps a table by key, exec::keyed_rounds, its recurring.name a work table lent to each round and taken back, not copied), Function (functions in FROM), Virtual (catalog tables), Window (below). The executor runs them as iterators; a join stashes its right input, sorts and aggregates take their input — each within work_mem, below. A Project run by the session’s thread evaluates, on its first row, each call that reads no row — not volatile, its arguments constants, parameters or the enclosing rows’ values (fixed for the plan’s run: it is built again for each) — and uses the value for every row (exec::row_free_evaluated; PostgreSQL folds stable functions of constants at execution start the same way): a stable function is the same within a statement, so embed(q, m) beside each row’s vector in a ranking is one model-cache lookup, not one a row (§M14.24 R4). A call that fails then is left to fail on its row; an expression holding a subquery is left whole (a copy’s plan is not the one the statement’s maps know by address: columns needed, measurements, cached rows).

Window functions (window, §M14.27 S4). f(…) OVER (PARTITION BY … ORDER BY … frame), a WINDOW clause’s named windows (one refining another as PostgreSQL allows), every aggregate over its frame and row_number, rank, dense_rank, percent_rank, cume_dist, ntile, lag, lead, first_value, last_value, nth_value. The binder puts the windows above the grouping and HAVING, below the projection, DISTINCT and ORDER BY: for each window (the calls with the same partition and order, in the order they first appear) a Sort by its partition’s keys, then its order’s — the one sort every ORDER BY uses, in parallel over a pipeline and past work_mem by runs — and a Window node, whose output is its input’s columns followed by one per call. The node takes a partition at a time — held in memory — and finds its peer groups once, comparing the keys in the rows (a key that is not a column computed into the row while it waits). Frames are PostgreSQL’s: ROWS, RANGE (an offset by the one ordering value: numbers, dates and times with an interval; its bounds found by binary search) and GROUPS, EXCLUDE CURRENT ROW | GROUP | TIES, offsets evaluated once, the default frame from the partition’s start to the current row’s last peer (the whole partition without ORDER BY). An aggregate’s frames are evaluated by the cheapest way that fits them (Leis et al., VLDB 2015): the whole partition — one state; frames from the partition’s start — one state grown row by row and finished at each distinct frame end, in place where the aggregate’s finish keeps its state (GroupAccumulator::finish_keeps_state: every built-in but string_agg and array_agg), else a copy (its partial combined into a fresh group); a frame of up to 64 rows — its rows added to a fresh group; larger frames — a segment tree of partial states over the partition’s rows, built when first needed, a frame the in-order combination of O(log n) nodes, for every aggregate whose states combine (the same partial / combine parallel aggregation uses, so the exact sums stay exact, and array_agg‘s order is kept); otherwise (string_agg, an extension’s aggregate without partial states) each distinct frame’s rows added to a fresh state. Consecutive equal frames reuse the last result; frames’ groups are taken from an accumulator renewed every 1024, so a long partition does not hold a state a row; each row’s frame is computed where it is wanted, not kept for the partition. A pipeline under the node gives its rows with room for the calls’ values (vector::rows_spare), so a row is not grown again. An exact sum is finished from an i128 where its chunks make one (ExactSum::total_small: the cast rounds once, the scaling by a power of two exact), which a running total does at every row. Errors are PostgreSQL’s (42P20 for a window where none is allowed, a nested call or a conflicting window; 42803 for a window inside an aggregate; 22013, 22014, 22016 for a negative frame offset, ntile or nth_value below one).

Ordered sets (quantile, buckets, §M14.27 S5). percentile_cont(f), percentile_disc(f) and mode() WITHIN GROUP (ORDER BY x [DESC]) — PostgreSQL’s ordered-set aggregates — and median(x) (DuckDB’s: percentile_cont(0.5) of numbers and intervals, percentile_disc(0.5) of any other ordered type). The binder gives an ordered-set aggregate (Aggregate::ordered_set) the arguments [x, f…, descending] and shows the call as written in EXPLAIN; WITHIN GROUP on another aggregate, an ordered-set one without it, or OVER one are errors (42809, 42809, 0A000). A fraction may be an array (an array results); a constant one is checked when the call is bound (Aggregate::check_direct), a computed one from the group’s first row; a fraction outside [0, 1] is 22003. Exact, by selection rather than by a sort: a group’s values are kept as they come — integers, booleans, dates, times and doubles as order-preserving 8-byte keys (a double’s bits, its sign flipped or all bits if negative, one NaN), other types as values — and its result is the values at a few ranks, each found by select_nth_unstable (introselect, O(n)), the next above the last; mode sorts its group and counts runs (ties to the first in the call’s order). States combine: a partial state is the fraction and the group’s values (keys as bytes), so values are collected on every worker and gathered for the selection. Past work_mem an accumulator moves its values to scratch space and adds to them there. Keys go as (group, key) records into a run, read back by partitions of half of work_mem: groups that fit are packed whole, a larger group is split by a count of its keys over 2¹⁶ slices of their range into ranges that fit — a slice of one key kept as a count, not a value — so each rank is selected in the one partition that holds it: each key written twice and read three times (to count, to partition, to select) whatever the run’s size — radix selection, not a merge sort’s log-many passes. Other values go into a Sorter of (group, value), read once in group order. percentile_cont interpolates as PostgreSQL does — the values at floor and ceil of f·(n − 1) in the call’s order, lo + t·(hi − lo) — with t and the interpolation each a fused multiply-add (PostgreSQL’s results as its arm64 build computes them; an x86-64 build rounds twice). width_bucket(x, low, high, count) is PostgreSQL’s over doubles (its steps, its errors: 2201G) and over decimals (exact: `floor(count·(x − low) / (high − low))

  • 1in wide integers), integers taking the doubles';width_bucket(x, bounds)counts the array's lower bounds at or belowx, any ordered type. histogram(x, low, high, count)is thecount + 2counts ofwidth_bucket's buckets (below the range first, past it last), histogram(x, bounds)thelen + 1`; counts combine, so a histogram aggregates in parallel.

Sketches (stablehash, hll, ddsketch, topk, §M14.27 S6). Approximate only by name, each within a stated bound and fixed in size. A sketch keeps hashes from stablehash — xxHash64 (seed 0) of a value’s key encoding, so equal values hash alike in any form (1.0, 1.00) and the hash is the same on every machine and version: a format, unlike fasthash‘s per-process seed. approx_count_distinct(x) is HyperLogLog++: sparse (the set of 25-bit hash prefixes with their ranks, near exact) up to 4096 prefixes, then 2¹⁴ registers (16 KiB, a standard error of 0.81 %), read by Ertl’s improved estimator — +, *, /, √ only, no bias tables, so an estimate is the same bits everywhere. approx_percentile(x, f) (approx_quantile, f a fraction or an array) is DDSketch: buckets of a factor (1 + α) / (1 − α) (α = 1 %), found by DDSketch’s cubically interpolated logarithm (exponent plus a cubic of the significand) — a quantile within α of the value at rank ⌊f · (n − 1)⌋; at most 2048 buckets a sign (about 17 decades at 1 %), the smallest magnitudes folded into the least kept past that; zero, the infinities and NaN counted apart and ordered as SQL orders them. Its error is relative to the value, so on data far from zero (timestamps, 1e9 + …) a bucket spans millions and percentile_cont is the one to use. Both merge by maximum or by adding counts, and a sketch is a function of the values it saw — their order, the workers, row or column storage do not change its bytes (tested as a law in every executor). As values: the registered types hll and ddsketch (text form their canonical bytes in hex, casts to and from bytea), made by hll_agg(x) and ddsketch_agg(x [, α]), merged by hll_merge and ddsketch_merge, read by hll_count (hll_cardinality), ddsketch_quantile(s, f) and ddsketch_count — a rollup keeps a day’s sketch and merges a month from them. approx_top_k(x, k) and approx_top_k_counts(x, k) are the most frequent values and their counts, ties to the least value: Misra–Gries counts in the mergeable form (exact until more than 2C distinct values, C = max(1024, 8k), then the (C + 1)-th greatest count taken from all), each count low by at most (n − Σ counts) / (C + 1); exact and order-free while x has at most 2C distinct values, otherwise the same in every run of a plan (its states merge in the morsels’ order: it is not order_free).

Sampling (sample, §M14.27 S7). FROM t TABLESAMPLE BERNOULLI (p) or SYSTEM (p), p a percentage, optionally REPEATABLE (seed) — PostgreSQL’s grammar and error codes (2202H a percentage outside 0–100 or NULL, 2202G a NULL seed, 42704 another method, 42809 on a CTE or a view). The binder puts a filter over the table’s scan, so the sample composes with everything a scan does (columns, pushed-down predicates, partitions). With REPEATABLE, a row is in the sample when stablehash of its primary key (all its columns without one), seeded by the seed’s bits, falls below p / 100 of the hash space: the same rows on every run, worker count, executor, version and machine, in row and column storage alike, and a smaller p’s sample within a larger one’s. Without it, each row is taken with probability p / 100 from a per-thread SplitMix64 seeded from the database’s random source — a new sample each statement. SYSTEM samples rows as BERNOULLI does (no block of storage is skipped yet). hash_unit(key [, seed]) is the same hash as a double precision in [0, 1) — WHERE hash_unit(id) < 0.8 a training set and >= 0.8 its test set, stable everywhere. random() is PostgreSQL’s, a double in [0, 1) from the same per-thread generator. Both draws are volatile but parallel-safe (ScalarFunction::parallel_safe, PostgreSQL’s PARALLEL SAFE; by default a function is unless it is volatile): their calls do not depend on one another, so a scan sampled without REPEATABLE runs on every CPU. reservoir_sample(x, n [, seed]) returns n of the non-NULL values (all of them when fewer) as an array, every set of n equally likely: Li’s Algorithm L, the reservoir ANALYZE samples with (sample::Reservoir), seeded by seed (0 by default); reservoirs from the workers merge by drawing without replacement how many values each gives (from the rows each saw), so the result is uniform and the same every run of a plan — not order_free, its gaps computed with ln and exp. n is 1 to 10⁶ (22023 otherwise).

Drift and tests (drift, §M14.27 S8). Two samples of one column told apart by a boolean side — false the reference, true the sample compared (an integer 0 / 1 converts); a row with either NULL is left out, and a side without rows gives NULL. Named as scipy and scikit-learn name their counterparts, with their answers. ks_test(x, side) is the two-sample Kolmogorov–Smirnov test (ks_2samp): {statistic, p-value}, the statistic — the largest gap between the two empirical distribution functions, ties stepping together — found in integers (max |a·n − b·m| over m·n, rounded once); the p-value exact while neither side has more than 10,000 values (the share of random interleavings that leave the band, by the lattice-path recurrence, the outside counted directly so a small p keeps its digits), past that the Kolmogorov distribution at (√e + 0.12 + 0.11/√e)·D, e = m·n/(m + n) (Stephens; scipy’s asymp takes the finite-sample distribution — at 15,000 a side 0.4134 where this gives 0.4144). auc(score, label) is the area under the ROC curve, label true for the positives (roc_auc_score): the Mann–Whitney rank sum, ties counted half, in integers. psi(x, side [, bins]) is the population stability index over bins (10; 1 to 10,000) bins of equal frequency in the reference — the edges the reference’s values at ranks ⌊k·m/bins⌋, a value in the bin of the edges at or below it, ties in one bin — Σ (q − p)·ln(q/p), an empty bin’s share counted as 10⁻⁴ when the other side’s is not. These three keep each side’s values as the ordered sets do (quantile::Doubles, work_mem, spilling, combined from the workers) and walk both in ascending order once, the compared side’s distinct values held in memory up to half of work_mem and read back from scratch space past it. Over categories (any type, equal by the key encoding): js_divergence(x, side), the Jensen–Shannon divergence of the two sides’ distributions in base 2 (0 to 1; scipy’s jensenshannon(p, q, base=2) squared), and chisq_test(x, side), Pearson’s χ² test of homogeneity on the 2 × k table (chi2_contingency, Yates’ correction at one degree of freedom): {statistic, p-value, degrees of freedom}, the p-value the regularized upper incomplete gamma function (series below a + 1, Lentz’s continued fraction above, ln Γ by Lanczos). Their counts are a map per group, at most work_mem of distinct values (54000 past it: bin first with width_bucket), summed in the values’ order, so neither result depends on the rows’ order. The ordered sets’ 8-byte keys are sorted by an LSD radix sort (quantile::sort_keys): a byte a pass, the bytes every key shares skipped, the standard library’s sort for fewer than 4096 keys or more than six differing bytes.

SUMMARIZE (summarize, §M14.27 S8b). SUMMARIZE t or SUMMARIZE <query> (DuckDB’s statement) returns one row a column of the source: column_name, column_type, min and max (as text, for numbers, text, enums, dates and times), approx_unique (approx_count_distinct), avg and std (numbers), approx_q25, approx_q50, approx_q75 (approx_percentile, numbers), count (the rows) and null_percentage (two decimals) — DuckDB’s columns, except that its approximate quartiles q25 … are named approx_ here, as nucleus names everything approximate. It is one aggregate query over the source (SELECT count(*), count(c0), approx_count_distinct(c0), min(c0)::text, … FROM (<source>) AS summarized(c0, …)), so one scan of every column, in parallel, its result turned into rows; a read (the MCP tool summarize_table runs it). Not yet a FROM item.

DESCRIBE (§M14.16 M6). DESCRIBE <statement> binds the statement without running it and returns a row for each parameter (kind parameter, its position, its type — the one its place gives it, as the extended protocol’s describe does; NULL when nothing tells) and for each result column (column, position, name, type, nullable): what nucleus codegen --queries reads (§8.37). A column is nullable = false only when it is known never to be NULL (the binder’s ScopeCol::not_null): a NOT NULL column read as it is — through subqueries, CTEs, inner joins and GROUP BY keys, not on the side an outer join pads (LEFT: the right; RIGHT: the left; FULL: both) —, RETURNING’s, a non-NULL literal, count, an ORDINALITY; a set operation’s column when every branch’s is; else true (an expression, an aggregate over no rows, a scalar subquery: may be NULL). A statement that does not check fails as it would (42703, 42P01, …); a DESCRIBE of a write writes nothing. nucleus’s own (PostgreSQL has none; MySQL’s DESCRIBE t describes a table).

Columns (prune, §M14.11). Before a query runs, its plan is walked from the top with the output columns wanted, each node adding what its expressions read (an uncorrelated subquery’s none of the row: it runs once — only its operand’s; a correlated one’s the columns of the row it reads — TPC-H Q16’s ps_suppkey NOT IN (SELECT …) had every column of partsupp decoded, its comments too: one worker 162.9 → 143.3 ms); a scan then decodes only the columns needed — the rest read as NULL, skipped in the encoding without being built (an out-of-line value not even fetched), and a row’s encoding not read at all past the last column wanted (count(*) reads none of it). A row table’s scan whose first step is a filter decodes the filter’s columns first and the other columns wanted for the rows it keeps only (late materialization, BatchSource::next_batch_tested): SELECT * … WHERE url LIKE '%x%' builds its hundred columns for the few rows that match. It runs when the other columns cost — one of variable length, or four or more, a decimal counting as two — and stops once more than half of a scan’s first two batches pass; a filter that fails has its rows decoded whole, to fail or be decided a row at a time as before. A column table’s scan does the same by segment run: the filter’s columns decoded (a dictionary’s codes where the filter tests them on its entries), the rows tested, and the other columns read for the rows kept — a value at a time from the segment’s stored column when at most a sixteenth are kept, else whole and gathered (ClickBench Q23 on column tables, ten workers, 109 → ~10–20 ms). Otherwise a row table’s batch decodes each row where the store keeps it (KvChunks::visit: the leaf held, the value in its cell, not copied into a chunk first — a row over 256 bytes copied alone first, WIDE_ROW, as a wide row’s column found by walking its encoding misses the cache); a row with a value stored out of line is taken back and read by chunk (its value fetched from the store, which a visit does not read), as is a scan merging side areas or the transaction’s own writes. An expression with a correlated subquery needs the columns of the row it reads; DISTINCT, set operations, CTEs and recursion need every column. Subqueries’ own plans decode only their columns too (a correlated index lookup into a column table, say, decodes the two columns it reads, not the segment’s every one). In a query, a correlated subquery’s result is kept by the values it reads of the rows around it (each level’s): a row with the same ones reuses it — WHERE l_quantity < (SELECT 0.2 * avg(…) WHERE l_partkey = p_partkey) runs once per part, not per line — unless it calls a volatile function or reads a table function (results of up to 1 024 rows, 65 536 per subquery). A grand total (an aggregate without GROUP BY) keeps one state, hashing no key.

Batches (vector, §M14.20). A table scan by the primary key (or of every row) and the filters and projections above it run as a pipeline, a batch at a time: a vector per column — integers, doubles and booleans typed, with a NULL mask; decimals of one scale their mantissas (Vector::Dec: a column store’s decimal segment as stored, a row table’s numeric column when its rows share a scale — 64-bit while each fits, Mantissas::Narrow, so a cached decimal column takes half the memory, else 128-bit; the kernels read either, widening as they go, §M14.20 W5); other types a value per row; a column nothing reads a NULL constant — and a selection of the rows still in play. The first batch is 64 rows, each next one twice the last, up to batch_size (default 1024; SET batch_size = 0 runs everything a row at a time). Rows are decoded from the stored encoding straight into the vectors. Expressions are evaluated a batch per call: kernels for integer and double arithmetic and comparisons (an integer widened against a double, as a row widens it), decimal +, -, * and comparisons on the mantissas (an integer a decimal of scale 0; +, - and comparisons at the larger scale, * at the sum — Decimal‘s rules, a result past 38 digits failing on a row in play; a comparison whose raising would overflow compared value by value; a 64-bit column against a constant that fits 64 bits by the integers’ comparison kernel), text and char(n) comparisons (a char(n) side without its trailing blanks, as a row compares it) and LIKE whose only wildcard is % (at the ends: a prefix, suffix or substring; within too: its parts found in order, each after the last — '%special%requests%'; substrings searched for by their first and last bytes, 32 places at a time), IN lists of constants over text, char(n) and integers (in a hash set past eight; other lists value by value, over the operand and the items only), comparisons of dates, times and timestamps of one kind, AND / OR / NOT (a filter’s AND narrows the rows a term at a time: each term over the rows no term before it held FALSE for — where a row’s AND evaluates it, so a term’s error is raised where a row’s is — and a row a term held NULL for dropped at the end; issue #2: TPC-H Q6 −8.6 %), IS NULL; an uncorrelated scalar, EXISTS or ARRAY subquery once (its rows are cached for the statement), an uncorrelated IN (subquery) as the list of its rows; function calls through the function’s batch kernel when it has one (ScalarFunction::call_batch, §8.12: substr over text and char(n) with constant positions), else casts and calls a value at a time over the batch’s vectors; CASE a branch at a time — each WHEN over the rows no earlier one took, its THEN over the rows it takes, ELSE over the rest, so each row evaluates what it would alone; an expression of constants (an operator, cast or immutable call of constant operands, an ARRAY[0.5, 0.95] of literals) once per batch, as a constant vector — not a value per row; anything else (correlated subqueries, decimal /, ILIKE, …) a row at a time, each row holding only the columns the expression reads (a long text it does not read is not copied). A row at a time, Expr::eval takes its common nodes (columns, literals, parameters, operators, IS NULL) itself and the others in a function of their own (eval_other), so each node of a row’s expression takes a small frame (480 bytes, not 1.7 kB). Text is a column of offsets and bytes (Arrow’s layout), char(n) the same as stored (blank-padded), a vector of its own from row and column storage alike; dates and times their integers (a date compared with a timestamp as microseconds, the date at midnight, as a row’s comparison has it). The kernels (nucleus-kernels) are dense loops over every position of a batch, written so the compiler vectorizes them and compiled once per CPU level — AVX2 and AVX-512 on x86-64, chosen at run time by feature detection; NEON, the baseline, on AArch64 — what can fail (an overflow, a division by zero) coming back as a mask the executor checks on the rows in play. Each has a scalar reference; crates/sql/tests/kernels.rs runs every kernel at every level the CPU has against it, on edge values, and the references against the SQL layer’s own definitions. Grand totals over a whole batch sum and compare integers in a kernel (exact, in two 32-bit halves); group keys hash through a seeded multiplicative hash. AND and OR evaluate their right side only on the rows the left one leaves undecided. Aggregates over a pipeline are vectorized when none has DISTINCT or ORDER BY (most DISTINCT calls the optimizer makes two groupings, §8.6): group numbers by key — one integer key by a direct index while the keys lie in a range of up to 65 536 values (the range found as they come, grown twofold), hashed as an integer past it; any other key by a salted table (keytable, DuckDB’s: slots of a group’s number and the upper half of its key’s hash, so a slot of another salt is passed over unread), the row’s key hashed and compared from the batch’s vectors as they are — no key built to look a group up, only a new group’s —, and each aggregate fed a batch at a time through Aggregate::grouped() — the built-ins’ states a column each, of the kind the aggregate and its argument need — a value for min, max, bool_and, bool_or, an exact sum and a row count for a sum or avg of integers or of decimals at one scale (their mantissas added), else a general state a group, which such a sum becomes when it meets another scale or kind —, updated in place from typed vectors — or row by row through its accumulators; past work_mem, rows of new groups go to partitions as below. A pipeline whose output becomes rows (for a sort, a join, the client) runs vectorized only when it filters. The result is the row-at-a-time one, errors included: a batch whose evaluation fails is run again a row at a time — the rows before the first failing one, then its error, so a LIMIT that ends first still ends without it. Under a limit on the rows read (a token’s ceiling) a statement runs a row at a time, since batches read ahead. EXPLAIN ANALYZE shows each node of a pipeline with its rows (times include the inputs’). The test kit’s scripts run with batches of the default size, of 3 rows and with none (crates/sql/tests/slt.rs); crates/sql/tests/vector.rs compares the three on chosen, failing and random queries. Integer sum and avg accumulate exactly (128 bits), so a sum overflows only when its result does, whatever the order.

Parallelism (vector, parallel, §M14.20). A pipeline’s scan (not one of a single key of a unique index: a row at most) splits into morsels at the KV’s split points (split_points), run by worker threads — up to parallel_workers (default 0: as many as the database’s CPUs, Kv::parallelism; 1 turns it off; the simulation offers one) — each with its own execution context over the transaction’s shared reads (KvTxn::shared) and the statement’s ambient state (who runs it, its time, its budget and deadline). An aggregate’s morsels are aggregated apart and their partial states combined in key order (GroupAccumulator::partial / combine, a capability: an aggregate without it — string_agg, whose separators belong to rows — runs in one pass). Many groups (16 384 partial ones or more) in no order of their keys are merged on the workers too: each morsel splits its groups into 64 parts by their keys’ hashes, and each part is merged on a worker (ClickHouse’s two-level tables) — the rows then put in the order a single pass first saw them, the first error by that order (a combining one before any finishing one). All of it within work_mem (DuckDB’s radix-partitioned aggregation): the running morsels share half of it, a share each — past its share a morsel writes its groups’ partial states to scratch space, part by part, and goes on with an empty table —, a morsel done keeps its groups in memory only while those kept fit in the other half, and a part reads a morsel’s spilled groups back before those it kept, so each group’s place and the errors are those of a merge in memory. Merged rows past half of work_mem in all come a part at a time, each part’s in the order first seen, those that did not fit beside the others from scratch space. When every aggregate is order-free (not array_agg, not string_agg), a worker keeps one table across the morsels it takes, unless its second morsel shows its groups do not recur (then each morsel’s table is handed over as before); a group’s rank is its morsel and its place in it, a merge takes a group’s least, and the merged groups are finished in rank order — a single pass’s order whichever worker took which morsel. Groups in key order are merged as §8.6 says. The builtin states pass between workers compactly: count an integer (its own accumulator, a count a group), min, max, bool_and, bool_or their value, a sum of no doubles its value (or its integer sum’s bytes), an avg of no doubles the pair of its rows and that; what a group’s states take counts against work_mem as each accumulator says (GroupAccumulator::group_bytes: 24 bytes for such a sum, 32 for a value, 8 for a count); a group’s accumulators grow by half again, not a group at a time, and a single integer key is found and placed in one probe. A pipeline whose output becomes rows runs in rounds of a morsel per worker, each round’s rows given in morsel order (a morsel’s rows held for its round: once they pass its share of work_mem and are eight times the rows it read — a join that multiplies them — it and the morsels after it run on the statement’s thread, their rows given as they come) — one that only projects, too, unless a LIMIT stops it within 65 536 rows (vector::SERIAL_ROWS: then it streams on the statement’s thread, a round’s morsels would read more; the limit marks the chain below it) — a filter counts there only if it drops rows: one whose conditions are all the scan’s key range’s own (Access::serves: k >= $1 over a scan from $1) does not. So the result is a single pass’s — groups in the order first seen, rows in key order, the first error the one a single pass meets, a LIMIT stopping after the round it needs. UPDATE and DELETE find their rows the same way (vectorized, in parallel when they can be) when the table is keyed by a primary key — each row’s key computed from its values; a policy, or a table keyed by hidden row ids, scans row by row. A DELETE that needs no more of a row than its key — a row table with a primary key and nothing derived from its rows (no secondary index, no referencing foreign key, no embedding column, no column’s type being changed, not partitioned), no policy, no RETURNING, and no value stored out of line in its snapshot (one first of the table’s chunks; a row another transaction made long since conflicts with that write) — scans only the key’s and the filter’s columns and deletes by the keys (dml::deletes_by_key, issue #7). Sums of doubles and reals are exact (fsum::ExactSum, §M14.27 S1: Neal’s superaccumulator — the sum as an integer in units of 2⁻¹⁰⁷⁵, in 32-bit chunks held in 64-bit words, only the chunks touched kept; an addition or subtraction is three integer additions, add_product adds x·y exactly — the significands’ 106-bit product from one 128-bit multiplication, added as five chunks; a long sum — past 16,384 additions — also keeps Neal’s large accumulator over a window of 256 exponents: a bin per exponent field, each value’s significand one integer addition into its bin, and a product split by fma into its rounded value and its error (both exact doubles where its bits lie at or above 2⁻¹⁰⁷⁴), the bins folded into the chunks every 1,024 additions and before any read; the result rounded once to nearest even from the integer; a worker’s state passed as bytes — the chunks carried, all but the top in four bytes, without the zeros at either end — and added from them without building a state), so they do not depend on the order either; avg of doubles is the exact sum divided by the count and rounded once (ExactSum::mean), not the rounded sum divided (PostgreSQL’s, which rounds twice). So do the moments (moments, §M14.27 S2): var_samp / variance, var_pop, stddev_samp / stddev, stddev_pop, skewness, kurtosis, one GroupAccumulator for all, combinable, its state the row count and the power sums. Over doubles Σx … Σx⁴ are ExactSums, each power added exactly (x² one add_product; x² = h + l by a fused multiply-add, then x³ as h·x + l·x and x⁴ as h² + 2hl + l²), so the central sums are exact integers — C₂ = nΣx² − (Σx)², C₃, C₄ — formed in bigint::BigInt (sign and magnitude, base 2³², only at the end) and rounded once: the variance as C₂/(n(n−1)) rounded from the integer quotient and its remainder; the standard deviation the square root of that; skewness √(n(n−1))/(n−2) · C₃/C₂^1.5 and kurtosis (n−1)((n+1)C₄ − 3(n−1)C₂²)/((n−2)(n−3)C₂²) from the exact numerators, NULL below 3 (4) rows or with no spread, as DuckDB’s. Over integers and decimals the variance and standard deviation are PostgreSQL’s numeric_stddev_internal: Σx and Σx² exact in bigint::Wide<8> (512-bit two’s complement, no allocation a row), at the inputs’ largest scale; the result at PostgreSQL’s scale (select_div_scale: 16 significant digits, at least twice the input’s), half away from zero, the root an integer square root — the same digits, up to numeric’s 38 (beyond: 22003, where PostgreSQL prints 39). The two-variable aggregates (regression, §M14.27 S3) — corr, covar_pop, covar_samp, regr_slope, regr_intercept, regr_r2, regr_count, regr_avgx, regr_avgy, regr_sxx, regr_syy, regr_sxy, PostgreSQL’s, arguments (y, x), doubles — keep n and only the sums their result needs of Σx, Σy, Σx², Σy², Σxy (ExactSums; integers read from their vectors without a Value each), so Cxx = nΣx² − (Σx)², Cyy and Cxy = nΣxy − ΣxΣy are exact integers, and each result is one ratio of them rounded once (moments::ratio, Knuth’s long division in BigInt::div_big); corr the root of the exact Cxy²/(CxxCyy), rounded once (moments::sqrt_ratio: the floor of the root of the floor is the floor of the root, exact only if both steps were). PostgreSQL’s rules: a row with either value NULL left out; NULL without rows, for covar_samp with one, and where x does not vary (and y, for corr); r² 1 for a horizontal line; NaN where an infinite or NaN input enters. Not in parallel: an enclosing row (a correlated subquery’s own plan), EXPLAIN ANALYZE, a volatile function or a subquery the workers cannot run in the pipeline (below), groups in key order past work_mem in a morsel, or merged on the statement’s thread past it (then the single pass partitions). The buffer pool reads a missing page without holding its lock, so workers reading cold pages do not wait on each other; its shards and frames take a cache line each (128 bytes), and a hit is counted in its shard, so workers finding pages do not write one line (a lookup’s every descent starts at the same root).

Subqueries where workers evaluate (expr::ready_subqueries): an uncorrelated one runs once on the statement’s thread first, its rows cached and given to the workers; one that reads a volatile function or fails keeps the work on one thread, which meets it where a single pass would. A correlated one runs on the workers for each row, as it would on the statement’s thread, when the statement is a query (nothing it runs writes), no rows it inserted into a column table are held unstored on the thread, and the subquery reads only the row it runs for (not one further out) and nothing that differs by thread or run — no volatile function, no table function, no CTE, recursive CTE’s work table or catalog view, its own subqueries included (PostgreSQL’s rule for a correlated SubPlan in a parallel plan, the check recursing into it). A filter or projection whose subquery runs for each row over rows that are not a pipeline’s — a join’s (TPC-H Q20: a condition with a correlated subquery stays above a semi join) — runs on worker threads the way an index nested loop’s lookups do (exec::OnWorkers, below): its input read in blocks, each block’s pieces evaluated on the workers, the rows given in the input’s order, its error where a single pass would stop, and none from rows a LIMIT stops short of.

Memory (spill, §M14.11). What an operator holds is bounded by work_mem (SET work_mem = '256MB', or the database’s setting; default 64 MiB): past it, the rest goes to scratch space — the KV contract’s scratch() (§6.1), files in the data directory’s scratch/ — and is read back. Sorts sort records in chunks, each kept in memory while the sort’s chunks fit in work_mem and written to scratch space past it, then merge them by key ranges (sorter, below; ties keep the input’s order) — under a LIMIT (a sort right below it), only the rows it takes and skips, kept in a heap of that many once twice as many came (spill::Top, PostgreSQL’s bounded sort) while it fits, a row turned away by one comparison, and the full sort past work_mem; materialised CTEs, recursive CTEs’ rounds and results, and the rows a write collects before writing (INSERT … SELECT, UPDATE, DELETE, rewrites) are kept in memory up to the limit, the rest in a run; writes then apply them 4096 rows at a time. Index builds sort their entries within the same limit (§8.7, Index builds). Table functions stream (generate_series makes its rows as they are read). Hash aggregation, DISTINCT, UNION and INTERSECT / EXCEPT keep their groups, the rows seen, or the right side’s counts in memory up to the limit; past it, rows of new groups (rows not yet seen; both sides of a set operation) go to 32 partitions by a hash of their key, each taken in turn after the input — a partition too large splits again, up to four levels — so no aggregate’s state ever leaves memory, and each partition holds every row of its keys. Joins stash their right input: in memory, a hash join probes it by key and a nested loop reads it all for each left row (a full join marks the right rows matched and gives the rest after); past the limit, a hash join is a grace hash join (both sides partitioned by key, each pair joined in turn — a right side still too large splits again; rows with a NULL key match nothing, coming out padded for LEFT and FULL) and a nested loop reads the right side once per work_mem’s worth of left rows (a block nested loop, the matched right rows of a full join in a bitmap) — as a grace hash join’s partition does when four splits leave it too large (one key’s rows); its rows are given as they are found, never gathered (BlockJoin: a LIMIT stops it, and a join of 30,000 rows on a dozen keys no longer writes 2.4 GB of scratch space for its count(*)). A recursive UNION‘s rows seen are a hash set up to the limit; past it the same 32 partitions, each a list of runs: a round’s rows go to their partitions as they come and, at its end, each partition’s are checked against the runs it holds, the new ones given (to the result and the next round) and added as a run of their own (exec::Seen) — a 2,000,000-row walk’s peak +432 → +225 MB under 4 MB, its time unchanged; under the default 64 MB +5 %, 240 MB less. Still held whole: the validated reads of a transaction (§5.2), and a recursive query’s table USING KEY (one row a key; a round’s rows themselves spill). Subqueries run per row when correlated, once per execution otherwise (cached in the execution context) — unless unnested into a join (§8.6). Their rows are kept by which subquery it is (SubPlan::id, made by the binder and kept by copies), a correlated one’s by that and the outer values it reads — not by the address of its plan: a scan copies its filter while it runs (once per partition), and a dropped copy’s address went to the next, whose subqueries could lie the other way round. A hash join whose left side is a pipeline (a scan, its filters and projections) and whose right side fits in work_mem runs vectorized: the right rows hashed once (vector::JoinTable, its keys found as a grouping finds its groups — keytable: one integer key in IntKeys, a direct index over a narrow range; other keys in KeyTable, a probe’s key hashed and compared from the batch’s vectors with no key built; two integers as a pair in the executor’s own hash, fasthash —; each key’s row numbers side by side in one array, no allocation per key), the left side’s keys evaluated a batch at a time and probed — the batch’s lookups all first, then its output, so lookups that depend only on their keys overlap their cache misses (what prefetching does in a hash probe; no unsafe prefetch instruction), no key built for a lookup — on worker threads, morsels of the left scan in key order, when it is large — with the rows, their order and errors of the row-at-a-time join; a condition that is just the integer keys’ equality is not checked again per row. When the right side is a pipeline too, the workers collect it — morsels in key order, their rows and keys’ values joined in order, so the table is a single pass’s — a column at a time (columns::Columns: an array a column, typed while its values are of one kind — an integer 9 bytes, not a Value‘s 32 —, no allocation per row), unless it passes work_mem (then it is stashed, and spills). A right side that is not a pipeline (a join’s output, a group’s) is gathered in columns the same way, its keys then evaluated — after every row, as when stashed —, and probed as above; once the columns pass work_mem, the rows gathered so far and the rest are stashed instead. Joins inside pipelines: an inner, left, semi or anti hash join whose left side is such a pipeline is itself a step of it (vector::Step::Probe), so joins over joins, and the grouping, sort or projection above them, run as one pipeline, on the workers’ morsels of the lowest scan. Before it runs, vector::prepare makes each join’s table in turn — outermost first, as the row-at-a-time join runs its right sides —, with its key filter; the workers’ contexts get the tables (Ctx::join_tables), which drop once the pipelines that probe them are made. A probe step joins a batch into a batch: each left row’s matches in the table’s order, its columns gathered from the left batch and from the table’s columns (Columns::gather), a left join’s unmatched rows with NULLs, a semi or anti join’s rows by the selection alone; an on beyond the keys is evaluated over every candidate pair at once, and an error there runs the batch again a row at a time, so the rows before it and the error are the row-at-a-time join’s. A right side past work_mem is stashed, the pipeline above it does not run as one, and the row-at-a-time join takes the stashed rows and the tables made above them (vector::take_built) — nothing runs twice. Not with an enclosing row (a correlated subquery’s plan, which runs again per row); a recursive CTE’s term makes its tables each round. Key filters (keyfilter): once an inner or semi join that hashes its right side has that side in hand — narrowed by a filter, a join or a group, not a whole table — the integer values of each key go into a filter (their least and greatest; the values themselves when 64 or fewer, else a Bloom filter, a word a key, three bits in it) for the table scans below the probe side that key’s column comes from (through projections, filters, sorts, partitions and the joins that keep their rows: not a limit, a group, the padded side of an outer join). The scan drops a row whose key no right row has, before its own filter — that row would leave at the join —, and a column store skips the segments whose least and greatest values miss the keys’ range. The filter is made in every executor alike (a row at a time, by batches, on workers, past work_mem), so their rows and errors agree; an error on a row only the key filter drops does not come. EXPLAIN ANALYZE marks the scan (join key filter). A sort (sorter, §M14.27 S4·sort) takes each row and its keys as one record of bytes: the keys normalized — each a byte placing a NULL first or last, then its index encoding (encoding::encode_key_value), a descending key’s bytes inverted, so the records’ bytewise order is the keys’ —, then the keys’ values and the row’s (the scratch codec). A record is a few dozen bytes where a row of values is hundreds, and two compare by their first eight bytes as an integer, then by memcmp. Where a key column holds values whose encoding does not order as the comparison does (intervals, enums, registered types, arrays) or of two kinds (a UNION‘s integers and doubles), records compare by their key values. A sort of a pipeline runs a sorter a morsel on the workers (keys a batch at a time); a sorter fills a chunk of records (work_mem shared by twice the workers), sorts it stably and keeps it — in memory while the sort’s chunks fit in work_mem (sorter::Budget), else in scratch space with every 128th record’s key as an index. The merge cuts the keys into ranges by splitters sampled from the chunks (their indexes, on disk), finds each chunk’s share of a range by binary search (or through its index), and merges the ranges on worker threads, two a worker ahead of the reader, their rows given in order; ties go to the earlier chunk — the morsels’ order —, so the order is a single pass’s stable sort. Under 32 768 rows, or on one worker, one heap merge streams. Under a LIMIT each morsel keeps its own heap of the rows taken, a row built only when its keys enter it, and the heaps are merged the same way. A sort is not run when its input is already in its order (optimizer::sorted): a table is read in primary-key order — a row table’s tree, a column table’s segments and delta merged, a parallel scan’s morsels in key order —, through filters and projections, so an ORDER BY of a prefix of the key, ascending, is that order (the key is never NULL; ties, in a stable sort, keep the input’s order — the key’s — too; past the whole key, further keys change nothing), for keys of kinds whose encoding orders as ORDER BY does. ORDER BY id LIMIT 10 then reads ten rows. A projection left giving its input’s rows as they are is dropped (optimizer::same_rows). An index nested loop (JoinAlgo::Lookup, EXPLAIN: Index Nested Loop) runs its right side — a table’s scan by an index on the join keys, the left row’s values as Outer references — once per left row (inner, left, semi and anti joins). A lateral item’s join is one too (EXPLAIN: Nested Loop (per row)), its right side any plan; the optimizer’s passes keep it whole (not reordered, no semi join moved into its right side) and the column pruning keeps the left columns it reads. It runs on worker threads when it can — a lateral item’s right side too, where it is a scan (by a key range or an index method’s ranking, Access::Method) under filters, projections, a sort and a limit, each worker running it whole for its left rows (a worker’s statement work is not shared out again: budget::workers is 1 on a worker, whose transaction gives the index methods the shared reads and the database’s instance, parallel::SharedTxn): the left rows read in blocks (256 at first, each next twice the last, up to 16 384), a block cut into pieces the workers look up over the shared reads, the pieces’ rows given in the left rows’ order — a single pass’s rows, and its error where it would stop (exec::OnWorkers, which a filter’s or projection’s subqueries share, §8.5 “Subqueries where workers evaluate”). A block starts √(rows / 5) threads at most (exec::threads_for: a thread’s start and join cost 10–17 µs, a lookup 2–2.6 µs, measured), so one of under 20 rows — a recursive query’s small rounds, each a block — runs on the calling thread; a pipeline’s lookup step takes its batch the same way. Not under EXPLAIN ANALYZE, for an enclosing row, for a lookup or condition with a volatile call or a subquery the workers cannot run (vector::parallel_safe_in), or while a statement on the thread holds rows it inserted into a column table unstored (only that thread’s reads see them). Where its left side is a pipeline (a scan through filters, projections and hash joins’ probes) the join is that pipeline’s step (vector::Lookup, as a probe is): each left row of a batch looked up as above, the rows given made a batch again — so the steps above it, and an aggregate over it, run on the workers with the scan, morsel by morsel (same conditions; exec::lookups_parallel_safe). A lateral table function (JSON_TABLE‘s rows, json_path_query, generate_series, unnest, …) is such a lookup when it says it is a function of its arguments alone (TableFunction::parallel_safe, false unless a function says so): each left row’s call runs on a worker. A lookup’s own scan, by its one key value, runs a row at a time (vector::rows declines a scan by an enclosing row’s key: a pipeline made for each lookup cost more than its few rows) — and where it reads by a key equal to the left row’s values, its range open beyond them (the whole primary key, a prefix of it, or a secondary index’s columns: exec::KeyLookup), not even that: the key is encoded from the left row once and its rows read — the whole primary key’s one row by the storage’s get, any other key’s range as the scan reads it — the scan’s filter and projection applied to them, no plan built (the right side’s plan is built for a left row after all where a value is not its key column’s type exactly, under EXPLAIN ANALYZE, for a validated read, or with a hash join’s key filter on the scan). A pipeline with a lookup step is cut into morsels as small as two leaves’ rows (KvRead::split_points_fine, where others take 64 leaves at least): a lookup costs a hundred times a row’s read, so a left table of a few thousand rows runs on the workers once rather than starting the lookups’ threads batch by batch. On a probe of 20,000 keys into 2,000,000 rows they took a primary-key join from 46 to 24 ms on one worker and 27.5 to 7 ms on ten (PostgreSQL 18’s index nested loop: 27 ms, not run in parallel), a secondary index’s from 52 to 38 ms on one and 28 to 13 on ten (PostgreSQL’s: 31) (PLAN.md, the perf phase’s reads by key, steps 2 and 3). A semi join gives each left row some right row matches, once; an anti join each left row none matches (a NULL key matches nothing, so its row comes out of an anti join); both give only the left’s columns, by hash, grace hash or block nested loop like the others. Where the left side is the smaller by estimate (half the right’s or less) a hash join hashes it instead (EXPLAIN: Hash Join (left hashed)): the right pipeline probes the left rows’ table a batch at a time, on worker threads when large, marking the rows it matches; then the left rows in order, those marked (semi) or not (anti). A probe gives at most four batches’ rows at a time (vector::probe_limit, 4,096 at least): a batch’s left rows whose matches pass it wait for the next step (a pipeline keeps them, the last part first, before it reads on) — a join that multiplies its rows gives them as the row-at-a-time join does, never a batch’s matches all at once (DuckDB’s probe gives a vector and keeps its place; PostgreSQL’s a tuple): a self-join of 60,000 rows on 12 values held 1.8 GB, now 32 MB, and runs 10 % faster. Expressions use three-valued logic, checked integer arithmetic (22003), division by zero (22012).