raghavyadav01 opened a new issue, #27690:
URL: https://github.com/apache/datafusion/issues/27690
### Describe the bug
A correlated `EXISTS` / `NOT EXISTS` subquery with a groupless `count(*)`
and a `HAVING` that reads both the count and an outer column returns wrong
rows. An outer row with no match in the subquery should see `count(*) = 0` and
have the `HAVING` evaluated against it. Instead that row is treated as if the
subquery produced no rows.
### To Reproduce
```sql
CREATE TABLE t1(t1_int INT) AS VALUES (1), (2), (3);
CREATE TABLE t2(t2_int INT) AS VALUES (2);
SELECT t1_int FROM t1 WHERE EXISTS (
SELECT count(*) FROM t2 WHERE t1.t1_int = t2.t2_int
HAVING count(*) + t1.t1_int > 1
) ORDER BY 1;
-- main: 2
-- DuckDB 1.5.6: 2, 3
SELECT t1_int FROM t1 WHERE NOT EXISTS (
SELECT count(*) FROM t2 WHERE t1.t1_int = t2.t2_int
HAVING count(*) + t1.t1_int > 1
) ORDER BY 1;
-- main: 1, 3
-- DuckDB 1.5.6: 1
```
For `t1_int = 3` there is no match, so `count(*) = 0` and `0 + 3 > 1` is
true. The row should be kept by `EXISTS` and removed by `NOT EXISTS`.
### Expected behavior
`2, 3` and `1`. An error would also be better than the wrong rows, as
suggested in #5492.
### Additional context
This is the remaining shape from #24960 (see
https://github.com/apache/datafusion/issues/24960#issuecomment-6506156269). The
other shapes there are fixed on main (checked on 538ef6adb).
In `build_join` (`decorrelate_predicate_subquery.rs`), the `HAVING`
condition becomes a join filter that reads the aggregate output.
`reads_agg_output` is then true, so the rewrite falls back to the uncompensated
plan, and unmatched outer rows never see the empty-input count. I'd like to
send a fix that keeps the subquery correlated in this case, so the query errors
instead, the same way #26942 does for scalar subqueries.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]