Bug #121958 LIMIT 0 and impossible WHERE evaluate materialized derived expressions
Description:
An outer zero-row condition does not prevent an expensive constant derived table or CTE from being evaluated.
The main query and SELECT 1 LIMIT 0 both returned the same empty result and created no tables. Across three alternating runs, the baseline took 10.9, 11.0, and 11.4 ms, while the derived-table query took 2011.8, 2012.2, and 2011.6 ms: 175.8–184.7 times slower.
EXPLAIN FORMAT=TREE for the slow query itself took 2011.8 ms and reported:
-> Zero rows (Zero limit) (cost=0..0 rows=0)
A variant using a shared one-row CTE above WHERE FALSE had the same behavior. Its baseline and slow query returned identical empty results. The baseline took 11.2, 11.4, and 11.4 ms; the CTE query took 2012.9, 2012.5, and 2012.3 ms, or 176.3–180.4 times longer. Its plan reported:
-> Zero rows (Impossible WHERE) (cost=0..0 rows=0)
LIMIT 0 and WHERE FALSE determine that no rows can be returned, so the two-second child evaluation is unnecessary. The fast statements demonstrate that the zero-row result can be produced without evaluating the child.
How to repeat:
Run as root. The main case creates no persistent objects:
SELECT 1 LIMIT 0;
SELECT 1
FROM (SELECT SLEEP(2) AS expensive_value) AS d1
LIMIT 0;
EXPLAIN FORMAT=TREE
SELECT 1
FROM (SELECT SLEEP(2) AS expensive_value) AS d1
LIMIT 0;
The two SELECT statements return the same empty result, but the second SELECT and its EXPLAIN each take approximately two seconds.
The following variant uses a shared CTE and an impossible outer WHERE:
DROP DATABASE IF EXISTS db1;
CREATE DATABASE db1;
DELIMITER //
CREATE FUNCTION db1.slow_value() RETURNS INT
NO SQL
BEGIN
DO SLEEP(2);
RETURN 7;
END//
DELIMITER ;
SELECT CAST(NULL AS SIGNED) AS x WHERE FALSE;
WITH shared_value AS (
SELECT db1.slow_value() AS x
LIMIT 1
)
SELECT a.x AS x
FROM shared_value AS a
JOIN shared_value AS b
WHERE FALSE;
EXPLAIN FORMAT=TREE
WITH shared_value AS (
SELECT db1.slow_value() AS x
LIMIT 1
)
SELECT a.x AS x
FROM shared_value AS a
JOIN shared_value AS b
WHERE FALSE;
The two SELECT statements again return the same empty result, but the CTE query takes approximately two seconds.
Suggested fix:
Apply known zero-row conditions such as LIMIT 0 and an impossible outer WHERE before preparing or eagerly materializing constant derived tables and CTEs.
Portions of this website are copyright © 2001, 2002 The PHP Group
Page generated in 0.039 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.