I have a (what it seems to me) simple query which fails to run on a simple table, the error is:
Out of sort memory, consider increasing server sort buffer size
These are the SQL statements which I’m trying to run:
CREATE TABLE `permissions` ( `id` INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`), UNIQUE KEY `name` (`name`) )ENGINE=InnoDB AUTO_INCREMENT=11 CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; INSERT INTO `permissions` (`id`, `name`) VALUES (1,'ocjena_dobavljaca.view'), (2,'ocjena_dobavljaca.edit'), (3,'ocjena_dobavljaca.delete'), (4,'zaposlenici.view'), (5,'zaposlenici.edit'), (6,'zaposlenici.delete'), (7,'vatrogasni_aparati.view'), (8,'vatrogasni_aparati.edit'), (9,'vatrogasni_aparati.delete'), (10,'organizacijska_shema_drustva'); COMMIT; SELECT SUBSTRING_INDEX(name, '.', 1) as n, COUNT(*) as num, GROUP_CONCAT(name)as nn FROM permissions GROUP BY n
You can check it in this SQL Fiddle.
This answer states:
While raising sort_buffer_size can help queries queries with GROUP BYs and ORDER BYs, you are better off improving the queries that you can improve and adding indexes that can be used by the Query Optimizer.
but I don’t see any way to improve the query or add indexes to the table, as they are quite simple.
Increasing the sort_buffer_size
from 64K (default) to 256K solves the issue, but I’m not sure if this is the right solution.
The other solution is to make the query with a subquery (two SELECT
s), which seems a bit redundant:
SELECT n, COUNT(*) as num, GROUP_CONCAT(name)as nn FROM ( SELECT SUBSTRING_INDEX(name, '.', 1) as n, name FROM permissions) a GROUP BY n;
Can anyone explain why the error?