Why does MYSQL higher LIMIT offset slow the query down?

后端 未结 6 1156
忘掉有多难
忘掉有多难 2020-11-22 07:20

Scenario in short: A table with more than 16 million records [2GB in size]. The higher LIMIT offset with SELECT, the slower the query becomes, when using ORDER BY *prima

6条回答
  •  难免孤独
    2020-11-22 08:10

    MySQL cannot go directly to the 10000th record (or the 80000th byte as your suggesting) because it cannot assume that it's packed/ordered like that (or that it has continuous values in 1 to 10000). Although it might be that way in actuality, MySQL cannot assume that there are no holes/gaps/deleted ids.

    So, as bobs noted, MySQL will have to fetch 10000 rows (or traverse through 10000th entries of the index on id) before finding the 30 to return.

    EDIT : To illustrate my point

    Note that although

    SELECT * FROM large ORDER BY id LIMIT 10000, 30 
    

    would be slow(er),

    SELECT * FROM large WHERE id >  10000 ORDER BY id LIMIT 30 
    

    would be fast(er), and would return the same results provided that there are no missing ids (i.e. gaps).

提交回复
热议问题