Search code examples
mysqlcounter-cache

How do I optimize an ORDER condition to prevent filesort?


How do I avoid a filesort when I want to order a query by condition in MySQL?

ORDER BY (videos_count > 0) DESC, name

Would it be better to cache a has_videos boolean column as well as the count?


Solution

  • How about partitioning the query into two, first the ones with at least one video, then (only if needed) the rest:

    select *  from video_table  
    where video_count > 0
    order by name
    

    And if you need to go beyond those:

    select *  from video_table  
    where video_count = 0
    order by name