pingcap / pingcap/tidb

EXISTS and NOT EXISTS Subqueries Return Incorrect Count

Open
#67,853 4 comments 0 reactions 0 assignees View on GitHub
affects-8.5 ai-bugfix contribution may-affects-7.1 may-affects-7.5 may-affects-8.1 severity/critical sig/planner type/bug
Dominant language
Go
Stars
40.5k
Forks
6.2k
PR merge metrics
PR metrics pending

Description

## Bug Report

Hi, I found a bug in TiDB 8.5.6. A query containing correlated `EXISTS` and `NOT EXISTS` subqueries that reference a virtual generated column (`c0`) and apply the bitwise `NOT` operator (`~`) to a `CAST(t0.c1 AS DATETIME)` expression returns an incorrect result. The `COUNT` aggregate incorrectly evaluates to `1` when logically it should be `0` .

### 1. Minimal reproduce step (Required)

```sql
CREATE TABLE t0(c0 BLOB(100) AS (c1 > 0) VIRTUAL, c1 DOUBLE ZEROFILL);
CREATE TABLE t1 LIKE t0;
INSERT INTO t1(c1) VALUES (0.8);
INSERT INTO t0(c1) VALUES (0.6);
SELECT COUNT(CASE WHEN NOT EXISTS (SELECT 1 FROM t1 WHERE ~CAST(t0.c1 AS DATETIME) AND t0.c0 = t1.c0) THEN 1 END) AS count FROM t0 WHERE EXISTS (SELECT 1 FROM t1 WHERE ~CAST(t0.c1 AS DATETIME) AND t0.c0 = t1.c0); -- expect 0, actually return 1
+-------+
| count |
+-------+
| 1 |
+-------+
1 row in set, 1 warning (0.00 sec)
```

### 2. What did you expect to see? (Required)
```sql
SELECT COUNT(CASE WHEN NOT EXISTS (SELECT 1 FROM t1 WHERE ~CAST(t0.c1 AS DATETIME) AND t0.c0 = t1.c0) THEN 1 END) AS count FROM t0 WHERE EXISTS (SELECT 1 FROM t1 WHERE ~CAST(t0.c1 AS DATETIME) AND t0.c0 = t1.c0); -- expect 0, actually return 1
+-------+
| count |
+-------+
| 0 |
+-------+
1 row in set, 1 warning (0.00 sec)
```
### 3. What did you see instead (Required)
```sql
SELECT COUNT(CASE WHEN NOT EXISTS (SELECT 1 FROM t1 WHERE ~CAST(t0.c1 AS DATETIME) AND t0.c0 = t1.c0) THEN 1 END) AS count FROM t0 WHERE EXISTS (SELECT 1 FROM t1 WHERE ~CAST(t0.c1 AS DATETIME) AND t0.c0 = t1.c0); -- expect 0, actually return 1
+-------+
| count |
+-------+
| 1 |
+-------+
1 row in set, 1 warning (0.00 sec)
```
### 4. What is your TiDB version? (Required)
| Release Version: v8.5.6
Edition: Community
Git Commit Hash: https://github.com/pingcap/tidb/commit/ae18096e023780bb56bfce33698abec0d4640d0a
Git Branch: HEAD
UTC Build Time: 2026-04-14 07:15:36
GoVersion: go1.25.8
Race Enabled: false
Check Table Before Drop: false
Store: tikv |

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.