LATERAL sub-query with a join and ORDER BY ... LIMIT fails with Invalid column when correlating on the joined table
Author: bluestreak01Created Sep 30, 2026Updated Sep 30, 2026
A LATERAL sub-query fails to compile when its body joins two tables, has ORDER BY ... LIMIT, and its WHERE correlates to the outer row with an equality on the joined (not the first) table. The join type does not matter (INNER, LEFT and ASOF all fail). The same query correlated on the first table, or on a single-table body, returns rows.
Reproduced on master 641aa5fee5.
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.pk
FROM o JOIN LATERAL (
SELECT t.id, p.k pk
FROM t JOIN p ON t.id = p.id
WHERE p.k = o.k
ORDER BY t.id
LIMIT 1
) s
ORDER BY 1, 2, 3;Actual: [0] Invalid column: __qdb_outer_ref__0_k (the error position is 0).
Expected:
ok id pk
1 1 10
2 2 20
3 2 30Variants:
t LEFT JOIN port ASOF JOIN p ON (id): same error.- Select
p.kwithout an alias: same error. - Correlate on the first table instead (
WHERE t.v = o.v ORDER BY t.id, p.k LIMIT 1): returns the correct rows. - Single-table body (
FROM p WHERE p.k = o.k ORDER BY p.id LIMIT 1): returns the correct rows.
Found while working on #7674.
Source: questdb/questdb