[MDEV-22416] "pushdown" of MIN/MAX inside UNION Created: 2020-04-05  Updated: 2023-12-12

Status: Open
Project: MariaDB Server
Component/s: Optimizer
Fix Version/s: 11.5

Type: New Feature Priority: Major
Reporter: Oleksandr Byelkin Assignee: Sergei Petrunia
Resolution: Unresolved Votes: 2
Labels: optimizer

Issue Links:
Relates
relates to MDEV-22417 "pushdown" of MIN/MAX inside UNION wi... Open

 Description   

There is min/max optimization in case of single SELECT, i.e:

SELECT MAX(field) FROM table;

We check only index for max (or min) value.

But if we have (probably via VIEW)

SELECT MAX(field) FROM
   (SELECT field1 as field FROM table1
    UNION
    SELECT field2  FROM table2);

we get all tables in temporary table than scan it for max (min).

If we transform the above query to :

SELECT MAX(field) FROM
  (SELECT MAX(field1) as field FROM table1
   UNION
   SELECT MAX(field2)  FROM table2);

optimisation will be still possible.

The idea of optimization is to push MIN/MAX into each part of the UNION if possible (It might not be possible for some SELECTs in the UNION)

Optimization is not possible in case:

  • underlying SELECT has:
    • GROUP BY
    • HAVING
    • ORDER BY/LIMIT
    • aggregate functions
    • non numeric type of the MAX/MIN field
  • outer SELECT has:
    • WHERE (see MENT-694)
    • GROUP BY (see MENT-694)
    • EXCEPT/INTERSECT in addition to UNIONs
    • Only one "derived" table with the UNION

Also possible such transformation for COUNT (only for ALL UNION):

SELECT COUNT(*) FROM
   (SELECT field1 as field FROM table1
    UNION ALL
    SELECT field2  FROM table2);

to

SELECT SUM(count) FROM
   (SELECT COUNT(*) as count  FROM table1
    UNION ALL
    SELECT COUNT(*)  FROM table2);



 Comments   
Comment by Oleksandr Byelkin [ 2020-04-05 ]

As psergey mentioned there could be problems with type casting (need to be checked in transformation)

Comment by Julien Fritsch [ 2020-04-06 ]

sanja since the fixversion is missing, I've added N/A to ensure this get listed into the dev or maintenance list, but please adjust it later.

Comment by Oleksandr Byelkin [ 2021-03-01 ]

Current plans is to start working on this in April

Generated at Thu Feb 08 09:14:34 UTC 2024 using Jira 8.20.16#820016-sha1:9d11dbea5f4be3d4cc21f03a88dd11d8c8687422.