Wrong result for correlated EXISTS with rowid predicate when optimizer is enabled
What happens?
A correlated EXISTS query returns an incorrect result when the optimizer is enabled.
With the default optimizer settings, an INNER JOIN using the same predicate returns 1 row, while the corresponding EXISTS query returns 0 rows.
After disabling the optimizer with PRAGMA disable_optimizer, both queries return 1.
The right-hand table contains exactly one row, so for this test case the INNER JOIN and EXISTS forms should agree on whether the single left-hand row has a match.
The incorrect result only occurs with the optimizer enabled.
To Reproduce
CREATE TABLE t75(c0 INTEGER);
CREATE TABLE t0(c0 INTEGER);
INSERT INTO t75 VALUES (1);
INSERT INTO t0 VALUES (0);
SELECT 'INNER_JOIN' AS q, COUNT(*) AS n
FROM t75 l
JOIN t0 r
ON l.rowid <= r.rowid
AND l.c0 <> r.c0;
SELECT 'EXISTS' AS q, COUNT(*) AS n
FROM t75 l
WHERE EXISTS (
SELECT 1
FROM t0 r
WHERE l.rowid <= r.rowid
AND l.c0 <> r.c0
);With the optimizer enabled, I get:
INNER_JOIN | 1
EXISTS | 0The expected result is:
INNER_JOIN | 1
EXISTS | 1Disabling the optimizer makes both queries return the expected result:
PRAGMA disable_optimizer;
SELECT 'INNER_JOIN_optimizer_off' AS q, COUNT(*) AS n
FROM t75 l
JOIN t0 r
ON l.rowid <= r.rowid
AND l.c0 <> r.c0;
SELECT 'EXISTS_optimizer_off' AS q, COUNT(*) AS n
FROM t75 l
WHERE EXISTS (
SELECT 1
FROM t0 r
WHERE l.rowid <= r.rowid
AND l.c0 <> r.c0
);Result:
INNER_JOIN_optimizer_off | 1
EXISTS_optimizer_off | 1For the only rows in the two tables, both rowid values are 0, so:
l.rowid <= r.rowid
0 <= 0
TRUEand:
l.c0 <> r.c0
1 <> 0
TRUETherefore the predicate is satisfied.
Since t0 contains exactly one row, the EXISTS predicate should be true for the single row in t75, and the result should be 1 rather than 0.
OS:
Ubuntu 2404
DuckDB Version:
1.5.5
DuckDB Client:
JDBC
Hardware:
No response
Full Name:
Ann C
Affiliation:
Nanchang University
Did you include all relevant configuration (e.g., CPU architecture, Linux distribution) to reproduce the issue?
- Yes, I have
Did you include all code required to reproduce the issue?
- Yes, I have
Did you include all relevant data sets for reproducing the issue?
Yes
Source: duckdb/duckdb