Bug #121867 Correlated subquery with COUNT(DISTINCT) and HAVING returns the previous outer row's count when it finds no rows

Submitted: 22 Nov 22:50
Reporter: Ke Han Email Updates:
Status: Open Impact on me:
None 
Category:MySQL Server: Optimizer Severity:S2 (Serious)
Version:26.10.0 (trunk 06bcb0eb0ad), 8.4.13 OS:Any
Assigned to: CPU Architecture:Any

[22 Nov 22:50] Ke Han
Description:
A scalar subquery (or a LATERAL derived table) without GROUP BY that has
COUNT(DISTINCT ...), SUM(DISTINCT ...) or AVG(DISTINCT ...) in its select list
and a HAVING condition on another aggregate returns a wrong value for an outer
row for which the subquery finds no rows. Instead of 0 (COUNT) or NULL
(SUM, AVG) it returns the DISTINCT aggregate of the rows that the subquery read
for an earlier outer row, when HAVING rejected that earlier row's group.

Example, "number of distinct products of each customer whose total spend is
below 100":
  (SELECT COUNT(DISTINCT o.product) FROM orders o WHERE o.cust = c.id
   HAVING COALESCE(SUM(o.amount), 0) < 100)
returns 3 for customer 2, who has no orders. 3 is the number of distinct
products of customer 1, whose group HAVING rejected. The manual says "If there
are no matching rows, COUNT(DISTINCT) returns 0", and NULL for SUM() and AVG()
(https://dev.mysql.com/doc/refman/26.10/en/aggregate-functions.html).

There is no error or warning. INSERT ... SELECT and UPDATE ... SET col =
(subquery) store the wrong value, and DELETE ... WHERE (subquery) = 0 does not
delete the row. The result depends on the order in which the outer rows are
read: with ORDER BY c.id DESC the same query returns the right values, and so
does the same aggregation written as a LEFT JOIN with GROUP BY. The
traditional and the hypergraph optimizer (optimizer_switch
'hypergraph_optimizer=on') return the same wrong values.

Not affected: GROUP_CONCAT(DISTINCT ...), aggregates without DISTINCT, the
same subquery without HAVING, a HAVING that refers to the DISTINCT aggregate by
its alias, and a prepared statement executed again with other parameters.
A HAVING that repeats the DISTINCT aggregate (HAVING COUNT(DISTINCT b) = 0) is
affected.

How to repeat:
CREATE DATABASE m215; USE m215;
CREATE TABLE customers (id INT PRIMARY KEY, name VARCHAR(10));
INSERT INTO customers VALUES (1, 'big'), (2, 'new'), (3, 'small'), (4, 'new2');
CREATE TABLE orders (id INT PRIMARY KEY, cust INT, product INT, amount INT, KEY (cust));
INSERT INTO orders VALUES (1, 1, 10, 500), (2, 1, 11, 400), (3, 1, 12, 300),
                          (4, 3, 10, 20), (5, 3, 10, 30);

-- distinct products of each customer whose total spend is below 100
SELECT c.id, (SELECT COUNT(DISTINCT o.product) FROM orders o WHERE o.cust = c.id
              HAVING COALESCE(SUM(o.amount), 0) < 100) AS n
FROM customers c ORDER BY c.id;

-- the same with the outer rows read in the other order
SELECT c.id, (SELECT COUNT(DISTINCT o.product) FROM orders o WHERE o.cust = c.id
              HAVING COALESCE(SUM(o.amount), 0) < 100) AS n
FROM customers c ORDER BY c.id DESC;

-- the same aggregation without a subquery
SELECT c.id, IF(COALESCE(SUM(o.amount), 0) < 100, COUNT(DISTINCT o.product), NULL) AS n
FROM customers c LEFT JOIN orders o ON o.cust = c.id GROUP BY c.id ORDER BY c.id;

-- SUM(DISTINCT)
SELECT c.id, (SELECT SUM(DISTINCT o.product) FROM orders o WHERE o.cust = c.id
              HAVING COALESCE(SUM(o.amount), 0) < 100) AS s
FROM customers c ORDER BY c.id;

-- LATERAL
SELECT c.id, d.n FROM customers c LEFT JOIN LATERAL
  (SELECT COUNT(DISTINCT o.product) AS n FROM orders o WHERE o.cust = c.id
   HAVING COALESCE(SUM(o.amount), 0) < 100) d ON TRUE ORDER BY c.id;

-- the value is stored by INSERT ... SELECT and UPDATE
CREATE TABLE report (id INT PRIMARY KEY, small_products INT);
INSERT INTO report SELECT c.id, (SELECT COUNT(DISTINCT o.product) FROM orders o
  WHERE o.cust = c.id HAVING COALESCE(SUM(o.amount), 0) < 100) FROM customers c;
SELECT * FROM report ORDER BY id;
ALTER TABLE customers ADD COLUMN small_products INT;
UPDATE customers c SET c.small_products = (SELECT COUNT(DISTINCT o.product) FROM orders o
  WHERE o.cust = c.id HAVING COALESCE(SUM(o.amount), 0) < 100);
SELECT id, small_products FROM customers ORDER BY id;

-- a clean-up of the customers without small purchases (2 and 4)
DELETE FROM customers AS c WHERE (SELECT COUNT(DISTINCT o.product) FROM orders o
  WHERE o.cust = c.id HAVING COALESCE(SUM(o.amount), 0) < 100) = 0;
SELECT id FROM customers ORDER BY id;

-- minimal form
CREATE TABLE t1 (id INT PRIMARY KEY, b INT);
INSERT INTO t1 VALUES (1, 0), (2, 5);
CREATE TABLE t2 (id INT PRIMARY KEY, b INT);
INSERT INTO t2 VALUES (1, 1), (2, 2), (3, 2);
SELECT t1.id, (SELECT COUNT(DISTINCT t2.b) FROM t2 WHERE t2.b > t1.b HAVING COUNT(*) = 0) AS n
FROM t1 ORDER BY t1.id;

Result on 26.10.0 (8.4.13 returns the same), as (id, value):
  first SELECT:          (1, NULL) (2, 3) (3, 1) (4, 0)        <- customer 2: 3, expected 0
  ORDER BY c.id DESC:    (4, 0) (3, 1) (2, 0) (1, NULL)        correct
  LEFT JOIN + GROUP BY:  (1, NULL) (2, 0) (3, 1) (4, 0)        correct
  SUM(DISTINCT):         (1, NULL) (2, 33) (3, 10) (4, NULL)   <- customer 2: 33 (10+11+12), expected NULL
  LATERAL:               (1, NULL) (2, 3) (3, 1) (4, 0)        <- 3, expected 0
  report (INSERT ... SELECT):     (1, NULL) (2, 3) (3, 1) (4, 0)   <- 3 stored
  customers.small_products (UPDATE): (1, NULL) (2, 3) (3, 1) (4, 0) <- 3 stored
  customers left after the DELETE: 1, 2, 3                     <- expected 1, 3
  minimal form:          (1, NULL) (2, 2)                      <- expected (2, 0)

Customer 4 has no orders either and gets the right 0, because the group read
just before it (customer 3) passed HAVING.

Suggested fix:
In the zero-row case of implicit grouping, AggregateIterator::DoRead() calls
no_rows_in_result() on the select-list items and clear() on the sum functions:
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/it...

Item_sum::no_rows_in_result() resets the aggregator with aggregator_clear():
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/it...
but Item_sum_count overrides it with { count = 0; }, and Item_sum_sum (which
AVG inherits) with clear(), so an Aggregator_distinct keeps the tree of
distinct values and the endup_done flag of the previous execution:
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/it...
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/it...

When HAVING rejected the previous execution's group, the select-list aggregate
was not evaluated, so endup_done is still false, and Aggregator_distinct::endup()
recomputes the value from the stale tree (count = tree->elements_in_tree(), or
a walk over the tree for SUM/AVG):
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/it...
If the previous group passed HAVING, endup() had already run, endup_done is
true and the value set by no_rows_in_result() is kept, which is why only an
earlier rejected group shows the problem. A HAVING that repeats the aggregate
has its own Item_sum and Aggregator_distinct (EXPLAIN shows "Aggregate:
count(distinct t2.b), count(distinct t2.b)"), so the select-list one is still
not evaluated; an alias refers to the same item.

Resetting the aggregator in Item_sum_count::no_rows_in_result() and
Item_sum_sum::no_rows_in_result() as the base class does (aggregator_clear(),
i.e. Aggregator_distinct::clear(), which resets endup_done and the tree:
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/it...)
should give 0 / NULL here.

Portions of this website are copyright © 2001, 2002 The PHP Group

Page generated in 0.040 sec. using MySQL 8.4.7-u6-cloud

Timestamp references displayed by the system are UTC.
Content reproduced on this site is the property of the respective copyright holders.
It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.