[MDEV-23278] Incorrect Calculation while using Avg Function Created: 2020-07-23  Updated: 2023-04-27

Status: Confirmed
Project: MariaDB Server
Component/s: Optimizer
Affects Version/s: 10.4.8, 10.3, 10.4, 10.5
Fix Version/s: 10.4, 10.5

Type: Bug Priority: Major
Reporter: anup b Assignee: Sergei Petrunia
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Amazon RDS



 Description   

Avg Function reports incorrect query results in SELECT.

show variables like '%optimizer_switch%';

index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on,index_merge_sort_intersection=off,engine_condition_pushdown=off,index_condition_pushdown=on,derived_merge=on,derived_with_keys=on,firstmatch=on,loosescan=on,materialization=on,in_to_exists=on,semijoin=on,partial_match_rowid_merge=on,partial_match_table_scan=on,subquery_cache=on,mrr=off,mrr_cost_based=off,mrr_sort_keys=off,outer_join_with_cache=on,semijoin_with_cache=on,join_cache_incremental=on,join_cache_hashed=on,join_cache_bka=on,optimize_join_buffer_size=on,table_elimination=on,extended_keys=on,exists_to_in=on,orderby_uses_equalities=on,condition_pushdown_for_derived=on,split_materialized=on,condition_pushdown_for_subquery=on,rowid_filter=on,condition_pushdown_from_having=on

CREATE TABLE `avg_calc_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1

INSERT INTO avg_calc_test (name) values ('ORANGE'), ('BLUE'), ('BLACK'), ('ORANGE'), ('BLACK');

– correct result 2.00
SELECT
AVG(CASE WHEN name = 'orange' THEN 3 WHEN name = 'blue' THEN 2 WHEN name = 'black' THEN 1 ELSE 0 END) AS metric_val
FROM avg_calc_test;

--Incorrect result 0.99
SELECT * FROM (
SELECT
AVG(CASE WHEN name = 'orange' THEN 3 WHEN name = 'blue' THEN 2 WHEN name = 'black' THEN 1 ELSE 0 END) AS metric_val
FROM avg_calc_test
) T;

SET optimizer_switch="split_materialized=off";
--Incorrect result 0.99
SELECT * FROM (
SELECT
AVG(CASE WHEN name = 'orange' THEN 3 WHEN name = 'blue' THEN 2 WHEN name = 'black' THEN 1 ELSE 0 END) AS metric_val
FROM avg_calc_test
) T;



 Comments   
Comment by Alice Sherepa [ 2020-07-24 ]

Thanks a lot for the report!
Repeatable on 10.3-10.5 with InnoDB/MyIsam, on 5.5-10.2 results are correct.

CREATE TABLE t1 (id int);
INSERT INTO t1 values (3),(2),(1),(3),(1);
 
SELECT * FROM (SELECT avg(CASE 
	WHEN id=3 THEN 3 
	WHEN id=2 THEN 2 
	WHEN id=1 THEN 1 END) av FROM t1) t;

10.3 c86accc7ac9ea503dc7988e7921

SELECT * FROM (SELECT avg(CASE 
WHEN id=3 THEN 3 
WHEN id=2 THEN 2 
WHEN id=1 THEN 1 END) av FROM t1) t;
av
0.9999

Comment by anup b [ 2020-07-28 ]

Thank you!!
Can I please ask, if it will be fixed in next mariadb 10.4 minor version? Any idea about timeframes?

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