#7694·questdb

LATERAL sub-query with a join, GROUP BY and a mixed correlated WHERE fails with Invalid column

Author: bluestreak01Created Sep 30, 2026Updated Sep 30, 2026

A LATERAL sub-query fails to compile when all of the following hold:

  • its body joins two tables,
  • it has GROUP BY,
  • its WHERE correlates to the outer row with an equality on the joined (not the first) table and also has a non-equality correlation.

The join type inside the body does not matter (INNER and LEFT both fail). Each part on its own works: the same query without the join, without the non-equality conjunct, or with the equality on the first table returns rows.

Reproduced on master 641aa5fee5.

sql
CREATE TABLE o (ok INT, k INT, v INT);
INSERT INTO o VALUES (1, 10, 1), (2, 20, 2), (3, 30, 2);
CREATE TABLE t (ts TIMESTAMP, id INT, v INT) TIMESTAMP(ts);
INSERT INTO t VALUES ('2024-01-01T00:00:01', 1, 1), ('2024-01-01T00:00:03', 2, 2), ('2024-01-01T00:00:05', 3, 3);
CREATE TABLE p (ts TIMESTAMP, id INT, k INT) TIMESTAMP(ts);
INSERT INTO p VALUES ('2024-01-01T00:00:00', 1, 10), ('2024-01-01T00:00:02', 2, 20), ('2024-01-01T00:00:04', 2, 30), ('2024-01-01T00:00:06', 3, 10);

SELECT o.ok, s.id, s.c
FROM o JOIN LATERAL (
    SELECT t.id, count(*) c
    FROM t JOIN p ON t.id = p.id
    WHERE p.k = o.k AND t.v <= o.v
    GROUP BY t.id
) s
ORDER BY 1, 2;

Actual: [0] Invalid column: p.__qdb_outer_ref__0_k (the error position is 0, not the offending token).

Expected:

ok  id  c
1   1   1
2   2   1
3   2   1

Variants:

  • t LEFT JOIN p instead of t JOIN p: same error.
  • Drop AND t.v <= o.v: returns the correct rows.
  • Single table (FROM p WHERE p.k = o.k AND p.id <= o.v GROUP BY p.id): returns the correct rows.

The rewritten column name p.__qdb_outer_ref__0_k suggests that the LATERAL rewrite (LateralJoinRewriter) qualifies the outer-ref column with the joined table's alias when it rewrites the GROUP BY layer.

Found while working on #7674.