Skip to content

Subqueries: give each SELECT its own subqueries, one compiled form and a run context #2717

Open
0 of 2 issues completed

Description

@mathiasrw

Many merged pull requests fixed one subquery case each. Read together, they trace back to five design choices. This issue proposes removing those causes instead of patching each case. It collects the review issues filed on 2026-10-20 and 2026-10-21.

Why subqueries break

  1. A subquery does not belong to its SELECT. The parser puts every subquery of a statement into one flat list (yy.queries, and yy.exists for EXISTS), and the expression refers to it by position (queriesidx). Inside another subquery, a UNION branch or a view, the position points into the wrong list. Each construct has had to hand lists around: Fix nested subqueries in IN clauses #2187 (takes too many, causing A subquery before IN (SELECT ...) is evaluated as the wrong subquery #2707), Fix UNION ALL with subquery in NOT IN clause #2404 (UNION branches, correct), Fix error when creating view with subquery in alasql #2406 (views), Fix UNION with nested SELECT #2518 and Fix multi-level nested scalar subquery evaluation #2550 (pass the outer list down at compile time and at run time).
  2. A subquery runs through many paths. Scalar and IN use queriesfn, EXISTS uses existsfn, FROM and JOIN each had their own data function (Fix for #1789: JOINs only return the second subquery #1800, Read a subquery in JOIN the same way as in FROM, so it can read a file #2676), and views and CTEs have their own. Each handles sync vs async, the RECORDSET modifier and errors on its own, so a fix in one path does not reach the others.
  3. Correlation is guessed. The outer row reaches the subquery as an untyped object p. Whether a subquery depends on it is guessed from table names (Optimize IN/NOT IN subquery performance with intelligent caching and correlated subquery detection #2281), which misses unqualified names (Correlated subquery with an unqualified outer column returns no rows #2644). Grouped SELECTs needed a copied row per group (Fix correlated subqueries in grouped selects #2514). UPDATE stores params on the parsed statement so a subquery can see it ([WIP] Fix variable binding in subquery for UPDATE statement #2534).
  4. Run state lives on compiled objects. subqueryCache on the query, self.params on the statement, and queriesfn patched during a run. That breaks cached and overlapping runs (Cached statements hold per-run state, so two runs of the same SQL at once overwrite each other #2596).
  5. Shape rules are checked case by case. A scalar subquery may return at most one row and one column, IN needs one column, EXISTS gives a boolean. Each rule is a separate patch (Fix EXISTS Function for Subqueries (Issue #1904) #1939, Fix: Add validation for INSERT VALUES with multi-column subqueries #2402) or not checked.

Proposal

  1. Each SELECT owns its subqueries. The parser starts a new list when a SELECT begins and closes it when the SELECT ends, as Fix UNION ALL with subquery in NOT IN clause #2404 already does for UNION branches. The subquery node holds its SELECT directly (Op.right already does), so queriesidx and every hand-over go away (Give each SELECT its own list of subqueries from parsing on #2666).
  2. A binding step between parsing and code generation. It builds a chain of scopes, one per SELECT, each with its sources and a link to the outer scope, and resolves every column to a scope level, a source and a column. A subquery is correlated exactly when one of its columns resolves to an outer scope: decided at compile time, for unqualified names and any depth, without guessing. A grouped outer query exposes the group row through the same scope.
  3. One compiled form with a declared kind. Every subquery compiles to run(ctx, outerScope) -> rows with a kind: SCALAR, IN, EXISTS or TABLE. A small wrapper per kind applies the shape rules: an error for more than one row in SCALAR, a set for IN, stop at the first row for EXISTS (Review #1939 for code improvements: EXISTS runs its whole subquery for every outer row #2678). FROM, JOIN, views and CTEs share one TABLE source with one sync/async path.
  4. A run context carries the run state. Parameters, outer rows and caches travel in a ctx object passed down; compiled statements stay unchanged after compiling. The cache policy follows from step 2: an uncorrelated subquery runs once per run; a correlated one runs per outer row, optionally cached by the outer values it uses.
Pull request Removed by
#2187, #2404, #2406, #2518, #2550 1 (no shared list)
#1800, #2676, #1939, #2402 3 (one compiled form, kind wrappers)
#2281, #2514, #2534 2 and 4 (scopes, run context)
#2397 the test matrix below

Test matrix

Most of these pull requests fixed one combination of: kind (scalar, IN, EXISTS, FROM, JOIN) × position (SELECT list, WHERE, HAVING, ON, view, CTE) × correlated or not, qualified or unqualified × depth (one to three levels) × inside a UNION branch or not × grouped or not. Generating those combinations and comparing each result with SQLite (#2593) shows the missing ones before users do.

Before you start

Step 1 of the order below (each SELECT owns its subqueries) and the test matrix can start now. The other steps build on #2723 (node classes and the bind step) and #2724 (run context and sources), so they wait for those.

Ground rules

  • Results stay as in 4.x. Only the bugs a pull request names may change results; the SQLite rules come in 5.0.
  • Small steps, each its own pull request, in the order below.
  • Each pull request passes the full test suite and the parity check in test/parity/ against the build before it.

Order

  1. SELECT owns its subqueries (Give each SELECT its own list of subqueries from parsing on #2666). Behaviour stays the same and existing tests cover it; fixes A subquery before IN (SELECT ...) is evaluated as the wrong subquery #2707. 4.x.
  2. One compiled subquery form and one TABLE source. 4.x.
  3. Run context, from Query runs: state of one run kept on the cached statement, and separate sync and async paths #2724 (starting with Cached statements hold per-run state, so two runs of the same SQL at once overwrite each other #2596). 4.x.
  4. Binding step, from Expressions: identity by text and column lookup while generating code #2723, keeping the v4 rule for ambiguous names. 4.x. Making ambiguous names fail, as decided for 5.0 on Built-in functions read an unqualified column from the first table in a JOIN #2615, is a separate step in 5.0, with a dialect keeping the v4 rule.
  5. The SQLite test matrix. Can start now and protects every step above.

The same pattern in other areas

Code generation resolves names, checks rules and handles run state while it builds strings; there is no resolved layer between parser and code generator. The same root shows in expression text used as identity (#2675), tree walkers written by hand per node type (#2195), each statement resolving db.table itself (#2705), window functions computed on output rows (#2690, #2702), and run state on compiled statements (#2596). A binding step with one generic child walker, plus a run context, addresses those too.

Review issues behind this: #2666, #2667, #2668, #2678, #2679, #2680, #2688, #2707, #2708, #2713.

Sub-issues

Sub-issues

0 of 2 Issues completed
Loading 2 sub-issues

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions