Inconsistent Results Between COUNT and SUM with Common Logical Conditions in SQL Queries
- Dominant language
- Go
- Stars
- 40.5k
- Forks
- 6.2k
- PR merge metrics
- PR metrics pending
Description
## Bug Report
The two SQL queries have a common sub-clause:`v0.c1 >= v0.c0 OR v0.c1 LIKE 'z%'`
Both queries essentially evaluate the same logical conditions. The first query directly counts the number of rows meeting the conditions, while the second query counts the number of TRUE evaluations from a subquery.
If a row meets either condition, it is counted as 1 in the second query and is included in the count in the first query.
Therefore, both statements should yield the same result, as they are counting the same set of rows based on the same conditions.
### 1. Minimal reproduce step (Required)
```sql
drop table if exists t0;
drop view if exists v0;
CREATE TABLE t0(c0 VARCHAR(255) COLLATE utf8mb4_general_ci);
INSERT INTO t0(c0) VALUES ('B');
CREATE VIEW v0(c0, c1) AS SELECT DISTINCT t0.c0, 'a' FROM t0;
SELECT COUNT(*) FROM v0 WHERE v0.c1 >= v0.c0 OR v0.c1 LIKE 'z%';
SELECT SUM(count) FROM (SELECT (v0.c1 >= v0.c0 OR v0.c1 LIKE 'z%') AS count FROM v0) AS asdf;
```
### 2. What did you expect to see? (Required)
return the same result.
### 3. What did you see instead (Required)
```sql
SELECT COUNT(*) FROM v0 WHERE v0.c1 >= v0.c0 OR v0.c1 LIKE 'z%';
+----------+
| COUNT(*) |
+----------+
| 0 |
+----------+
1 row in set (0.01 sec)
SELECT SUM(count) FROM (SELECT (v0.c1 >= v0.c0 OR v0.c1 LIKE 'z%') AS count FROM v0) AS asdf;
+------------+
| SUM(count) |
+------------+
| 1 |
+------------+
1 row in set (0.00 sec)
```
### 4. What is your TiDB version? (Required)
```
mysql> select version();
+--------------------+
| version() |
+--------------------+
| 8.0.11-TiDB-v7.5.1 |
+--------------------+
1 row in set (0.00 sec)
```
Contributor guide
Research direction
Start by running the supplied SQL reproducer on TiDB v7.5.1 and compare the COUNT and SUM results. Trace the SQL expression and aggregation execution paths to identify the discrepancy, then add a regression test showing that both queries return the same result.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- go, mysql, sql
- Domain
- databases
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100