Skip to content

A subquery before IN (SELECT ...) is evaluated as the wrong subquery #2707

Done

Description

@mathiasrw

A scalar or EXISTS-style subquery that comes before an IN (SELECT …) in the same statement can be evaluated as the wrong subquery. The result depends on the order of the subqueries in the text, and there is no error.

Measured on develop (94ccf84), next to SQLite 3.43:

CREATE TABLE st (x INT); INSERT INTO st VALUES (1), (2), (3);
CREATE TABLE su (x INT, y INT); INSERT INTO su VALUES (2, 20), (3, 30);
Query AlaSQL SQLite
SELECT x, (SELECT MAX(y) FROM su) AS m FROM st WHERE x IN (SELECT x FROM su) m = 2 on both rows m = 30
SELECT x FROM st WHERE x < (SELECT MAX(x) FROM su) AND x IN (SELECT x FROM su) no rows 2
SELECT x FROM st WHERE x IN (SELECT x FROM su) AND x < (SELECT MAX(x) FROM su) 2 2

Cause

The grammar actions for IN (SELECT …), NOT IN (SELECT …) and op ALL/ANY (SELECT …) (src/alasqlparser.jison, from #2187) take every subquery collected so far in yy.queries, attach them to the inner SELECT and empty the list. Subqueries that were parsed earlier in the outer statement (a scalar subquery in the SELECT list, an earlier condition) are moved into the inner SELECT too. The outer statement's queriesidx then points at the wrong entry.

Direction

Only the subqueries inside the parentheses belong to the inner SELECT. Marking where the inner SELECT starts (as UnionOp already does with yy.queriesStack), or giving each SELECT its own list from parsing on (#2666), fixes this. It is a wrong result, so it can go into 4.x.

Related: #847, #2187, #2666, #2679.

Activity

  1. added this to the v4.x Focus milestone on Oct 20, 2026
  2. mathiasrw commented on Oct 21, 2026

    @mathiasrw
    MemberAuthor

    Another form from the sqllogictest run (test/index/view/100/slt_good_3.test, 43 rows where SQLite gives 42): with two IN (SELECT ...) in one statement, the first IN is checked against the second subquery. develop 06211a0 and npm 4.20.1, SQLite 3.43.2:

    Query AlaSQL SQLite
    SELECT 1 IN (SELECT 9) AS p, 1 IN (SELECT 1) AS q p true, q true 0, 1
    SELECT a FROM t WHERE a IN (SELECT 9) OR (a = 0 AND a IN (SELECT 1)) (t holds a = 1) 1 no rows
  3. mathiasrw commented on Nov 26, 2026

    @mathiasrw
    MemberAuthor

    Fixed on main by #3082.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions