diff --git a/mysql-test/r/order_by.result b/mysql-test/r/order_by.result index 4cd9aebdf49..380687554d7 100644 --- a/mysql-test/r/order_by.result +++ b/mysql-test/r/order_by.result @@ -3207,3 +3207,33 @@ pk 2 3 DROP TABLE t1; +# +# MDEV-21044: Wrong result when using a smaller size for sort buffer +# +create table t1(a varchar(765),b int); +insert into t1 values ("a",1),("b",2),("c",3),("e",4); +insert into t1 values ("d",5),("f",6),("g",7),("h",8); +insert into t1 values ("k",11),("l",12),("i",9),("j",10); +insert into t1 values ("m",13),("n",14),("o",15),("p",16); +set @save_sort_buffer_size= @@sort_buffer_size; +set sort_buffer_size=1024; +select * from t1 order by b; +a b +a 1 +b 2 +c 3 +e 4 +d 5 +f 6 +g 7 +h 8 +i 9 +j 10 +k 11 +l 12 +m 13 +n 14 +o 15 +p 16 +set @@sort_buffer_size= @save_sort_buffer_size; +drop table t1; diff --git a/mysql-test/t/order_by.test b/mysql-test/t/order_by.test index 1ca258d1d48..999c7314139 100644 --- a/mysql-test/t/order_by.test +++ b/mysql-test/t/order_by.test @@ -2141,3 +2141,19 @@ INSERT INTO t1 VALUES (1),(2),(3); SELECT DISTINCT pk FROM t1 GROUP BY 'foo'; SELECT DISTINCT pk FROM t1; DROP TABLE t1; + +--echo # +--echo # MDEV-21044: Wrong result when using a smaller size for sort buffer +--echo # + +create table t1(a varchar(765),b int); +insert into t1 values ("a",1),("b",2),("c",3),("e",4); +insert into t1 values ("d",5),("f",6),("g",7),("h",8); +insert into t1 values ("k",11),("l",12),("i",9),("j",10); +insert into t1 values ("m",13),("n",14),("o",15),("p",16); +set @save_sort_buffer_size= @@sort_buffer_size; +set sort_buffer_size=1024; +select * from t1 order by b; +set @@sort_buffer_size= @save_sort_buffer_size; +drop table t1; + diff --git a/sql/filesort.cc b/sql/filesort.cc index 4f195f68059..bb3e73343ad 100644 --- a/sql/filesort.cc +++ b/sql/filesort.cc @@ -343,6 +343,7 @@ ha_rows filesort(THD *thd, TABLE *table, SORT_FIELD *sortorder, uint s_length, param.max_keys_per_buffer=((param.max_keys_per_buffer * (param.rec_length + sizeof(char*))) / param.rec_length - 1); + set_if_bigger(param.max_keys_per_buffer, 1); maxbuffer--; // Offset from 0 if (merge_many_buff(¶m, (uchar*) table_sort.get_sort_keys(),