Share this
The error SQLSTATE[HY001]: Memory allocation error: 1038 Out of sort memory, consider increasing server sort buffer size occurs when MySQL runs out of memory while sorting data. To resolve this issue, follow these steps:
1. Increase sort_buffer_size in MySQL Configuration
The sort_buffer_size determines the amount of memory allocated for sorting operations. Increasing it can help resolve the issue.
Option 1: Temporarily Increase sort_buffer_size (Session-Level)
Run the following command in MySQL to increase the buffer size for the current session:
SET SESSION sort_buffer_size = 4M;
(Default is usually 256K, so 4M is a reasonable increase.)
Option 2: Permanently Increase sort_buffer_size (Server-Level)
If the issue persists, edit the MySQL configuration file (my.cnf or my.ini):
- Locate the MySQL configuration file:
Linux: /etc/my.cnf or /etc/mysql/my.cnf
Windows: C:\ProgramData\MySQL\MySQL Server X.X\my.ini - Add or modify the following line under [mysqld]
sort_buffer_size = 4M
- Restart MySQL for the changes to take effect:
sudo systemctl restart mysql
Or
service mysql restart
2. Optimize Queries to Reduce Sorting Needs
- Use INDEXES on columns that are used for sorting (ORDER BY).
- Avoid ORDER BY RAND(), as it forces sorting in memory.
- Reduce unnecessary sorting by limiting result sets with LIMIT.
3. Check MySQL Available Memory
Ensure that MySQL has enough memory allocated. You can check the current value of sort_buffer_size using:
SHOW VARIABLES LIKE 'sort_buffer_size';
If your server has low RAM, consider upgrading hardware or optimizing other memory settings (innodb_buffer_pool_size, join_buffer_size, etc.).

Ravindra is a passionate full stack developer and dedicated blogger with a flair for crafting user-friendly web applications and insightful articles. With expertise spanning front-end and back-end technologies, Ravindra brings ideas to life through innovative coding solutions.