Bug #121379 Identical UNION operands return different values when counting an EXCEPT ALL CTE
Submitted: 28 Sep 8:25 Modified: 29 Sep 11:20
Reporter: jinxin gui Email Updates:
Status: Verified Impact on me:
None 
Category:MySQL Server: Optimizer Severity:S2 (Serious)
Version:8.0.46, 8.4.11, 9.7.2, 26.07 OS:Linux
Assigned to: CPU Architecture:Any
Tags: cte, except, UNION

[28 Sep 8:25] jinxin gui
Description:
A CTE containing two EXCEPT ALL operations is empty for the data below. However, two identical scalar expressions that count this CTE return different values when combined with UNION. The query returns both 2 and 3; it should return only 2.

How to repeat:
CREATE TABLE t1_query_expression (i INT);
CREATE TABLE t2_query_expression (i INT);
CREATE TABLE t3_query_expression (i INT);

INSERT INTO t1_query_expression VALUES (1), (1), (1);
INSERT INTO t2_query_expression VALUES (2), (2), (1), (1);
INSERT INTO t3_query_expression VALUES (2), (3), (3), (1), (1);

-- Actual: 0.
WITH ccte3 AS (
  SELECT * FROM t1_query_expression
  EXCEPT ALL
  SELECT * FROM t2_query_expression
  EXCEPT ALL
  SELECT * FROM t3_query_expression
)
SELECT COUNT(*) FROM ccte3;

-- Actual: 1 row, col1 = 2.
WITH ccte3 AS (
  SELECT * FROM t1_query_expression
  EXCEPT ALL
  SELECT * FROM t2_query_expression
  EXCEPT ALL
  SELECT * FROM t3_query_expression
)
SELECT DISTINCT (CAST((SELECT COUNT(*) FROM ccte3) AS SIGNED) + 1) + 1 AS col1;

-- Actual: 2 rows, col1 = 2 and col1 = 3.
WITH ccte3 AS (
  SELECT * FROM t1_query_expression
  EXCEPT ALL
  SELECT * FROM t2_query_expression
  EXCEPT ALL
  SELECT * FROM t3_query_expression
)
SELECT (CAST((SELECT COUNT(*) FROM ccte3) AS SIGNED) + 1) + 1 AS col1
UNION
SELECT (CAST((SELECT COUNT(*) FROM ccte3) AS SIGNED) + 1) + 1 AS col1;
```

Expected result: The last query returns one row, `col1 = 2`. Both `UNION` operands are identical, and `UNION` removes duplicate rows.
[29 Sep 11:20] Chaithra Marsur Gopala Reddy
Hi jinxin gui,

Thank you for the test case. Verified as described.