Bug #119692 The normal query generated a non-optimal query plan.
Submitted: 16 Jan 5:23 Modified: 16 Jan 8:09
Reporter: chi zhang Email Updates:
Status: Verified Impact on me:
None 
Category:MySQL Server: Optimizer Severity:S1 (Critical)
Version:8.0.44 OS:Any
Assigned to: CPU Architecture:Any

[16 Jan 5:23] chi zhang
Description:
Hi,

In the following tese case, there are two equivalent query, one is normal SELECT query, and another is prepared SELECT query. Typically, because prepared statements contain unknown literals, the query plan generated during their compilation is often suboptimal. As a result, their execution time is generally expected to be longer than that of a normal statement. However, in this example, although the prepared statement generates a more complex query plan, its execution time is consistently faster than that of the normal SELECT statement. So the normal SELECT may choose a faster query plan.

```
CREATE TABLE t0(c0 FLOAT ZEROFILL ) ;
CREATE TABLE IF NOT EXISTS t2 LIKE t0;
INSERT INTO t2(c0) VALUES(0.8228615521965937), (0.8228615521965937), (0.8228615521965937), (0.8228615521965937), (0.8228615521965937), (0.8228615521965937);
INSERT IGNORE INTO t0(c0) VALUES(59976104), (59976104);
SET PROFILING = 1;
EXPLAIN ANALYZE SELECT DISTINCTROW COUNT(CAST(0.781169564717212 AS DOUBLE)) AS ref0 FROM t0 INNER JOIN t2 ON  true;
SET @a = 0.781169564717212;
PREPARE prepare_query FROM 'EXPLAIN ANALYZE SELECT DISTINCTROW COUNT(CAST(? AS DOUBLE)) AS ref0 FROM t0 INNER JOIN t2 ON  true';
EXECUTE prepare_query USING @a;
DEALLOCATE PREPARE prepare_query;
SET PROFILING = 0;
```

This is the query plan of the normal SELECT:
```
-> Count rows in t0  (actual time=6.34..6.34 rows=1 loops=1)
```

This is the query plan of the prepared SELECT:
```
-> Aggregate: count(cast(0.781169564717212 as double))  (cost=4.66 rows=1) (actual time=0.036..0.0361 rows=1 loops=1)
    -> Inner hash join (no condition)  (cost=1.9 rows=12) (actual time=0.0247..0.0284 rows=12 loops=1)
        -> Table scan on t2  (cost=0.425 rows=6) (actual time=0.00263..0.00511 rows=6 loops=1)
        -> Hash
            -> Table scan on t0  (cost=0.45 rows=2) (actual time=0.0114..0.0144 rows=2 loops=1)
```

How to repeat:
```
CREATE TABLE t0(c0 FLOAT ZEROFILL ) ;
CREATE TABLE IF NOT EXISTS t2 LIKE t0;
INSERT INTO t2(c0) VALUES(0.8228615521965937), (0.8228615521965937), (0.8228615521965937), (0.8228615521965937), (0.8228615521965937), (0.8228615521965937);
INSERT IGNORE INTO t0(c0) VALUES(59976104), (59976104);
SET PROFILING = 1;
EXPLAIN ANALYZE SELECT DISTINCTROW COUNT(CAST(0.781169564717212 AS DOUBLE)) AS ref0 FROM t0 INNER JOIN t2 ON  true;
SET @a = 0.781169564717212;
PREPARE prepare_query FROM 'EXPLAIN ANALYZE SELECT DISTINCTROW COUNT(CAST(? AS DOUBLE)) AS ref0 FROM t0 INNER JOIN t2 ON  true';
EXECUTE prepare_query USING @a;
DEALLOCATE PREPARE prepare_query;
SET PROFILING = 0;
```
[16 Jan 8:09] Roy Lyseng
Thank you for the bug report.
Verified as described.