How do I fix a MySQL out of sort memory error?

ERROR 1038 (HY001): Out of sort memory, consider increasing server sort buffer size

Sort Buffer Size (sort_buffer_size) is a MySQL server system variable that can affect your query performance. It is defined on a per-session level, impacting your cluster’s memory consumption.

Warning
Changing sort_buffer_size can reduce query performance, increase overall memory consumption, and even crash your cluster. This process is highly specific to your workload and we do not recommend changing the default value. Please read its potential use cases and disclaimers before changing it.

To fix this error, increase sort_buffer_size to a value higher than its default of 256KB. Having sort_buffer_size over 5MB may significantly slow down memory allocation. To learn how to safely adjust sort_buffer_size, see our guide.