[MDEV-30324] Wrong result upon SELECT DISTINCT .. WITH TIES using index Created: 2023-01-02  Updated: 2023-02-15  Resolved: 2023-02-15

Status: Closed
Project: MariaDB Server
Component/s: Optimizer
Affects Version/s: 10.6, 10.7, 10.8, 10.9, 10.10, 10.11
Fix Version/s: 10.11.3, 11.0.1, 10.6.13, 10.7.8, 10.8.8, 10.9.6, 10.10.4

Type: Bug Priority: Major
Reporter: Elena Stepanova Assignee: Vicențiu Ciorbaru
Resolution: Fixed Votes: 0
Labels: 11.0-sel


 Description   

CREATE TABLE t (a int, b char(3), KEY (a));
INSERT INTO t VALUES (2,'foo'),(2,'bar'),(3,'baz'),(3,'qux');
 
SELECT DISTINCT a, b FROM t ORDER BY a FETCH FIRST 1 ROWS WITH TIES;
 
# Cleanup
DROP TABLE t;

10.6 0a67daad

SELECT DISTINCT a, b FROM t ORDER BY a FETCH FIRST 1 ROWS WITH TIES;
a	b
2	foo
2	bar
3	baz
3	qux

Reproducible with at least InnoDB, MyISAM, Aria.

The plan for the query is

EXPLAIN EXTENDED SELECT DISTINCT a, b FROM t ORDER BY a FETCH FIRST 1 ROWS WITH TIES;
id	select_type	table	type	possible_keys	key	key_len	ref	rows	filtered	Extra
1	SIMPLE	t	index	NULL	a	5	NULL	1	100.00	Using temporary
Warnings:
Note	1003	select distinct `test`.`t`.`a` AS `a`,`test`.`t`.`b` AS `b` from `test`.`t` order by `test`.`t`.`a` fetch first 1 rows with ties

The expected result is

a	b
2	bar
2	foo

It can be achieved by disabling the index:

SELECT DISTINCT a, b FROM t IGNORE INDEX (a) ORDER BY a FETCH FIRST 1 ROWS WITH TIES;
a	b
2	bar
2	foo
 
EXPLAIN EXTENDED SELECT DISTINCT a, b FROM t IGNORE INDEX (a) ORDER BY a FETCH FIRST 1 ROWS WITH TIES;
id	select_type	table	type	possible_keys	key	key_len	ref	rows	filtered	Extra
1	SIMPLE	t	ALL	NULL	NULL	NULL	NULL	4	100.00	Using temporary; Using filesort
Warnings:
Note	1003	select distinct `test`.`t`.`a` AS `a`,`test`.`t`.`b` AS `b` from `test`.`t` IGNORE INDEX (`a`) order by `test`.`t`.`a` fetch first 1 rows with ties


Generated at Thu Feb 08 10:15:24 UTC 2024 using Jira 8.20.16#820016-sha1:9d11dbea5f4be3d4cc21f03a88dd11d8c8687422.