Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To fetch last 10 record ,adding 'LIMIT' to MySQL queries make it faster?

Tags:

mysql

Can someone explain if i want to fetch last 10 records ,adding 'LIMIT' to MySQL queries make it faster? like

SELECT 
    *
FROM
    `table`
ORDER BY id DESC
LIMIT 50;

is there any other way to fetch last 10 record or is it faster?

like image 651
useless'MJ Avatar asked Nov 30 '25 07:11

useless'MJ


1 Answers

The problem with limit is it must order all the rows in the table before returning only the last 50, so it's always going to be slow and will get slower as the table grows (not scaleable).

The fastest way to get the last 50 is:

SELECT 
  *
FROM
  `table`
WHERE id > (SELECT MAX(id) FROM `table`) - 50

This will use the index on id to get the max id and again to get the top 50.


You should also try this slightly more complicated but potentially better optimisable:

SELECT 
  *
FROM
  `table`
WHERE id BETWEEN (SELECT MAX(id) FROM `table`) - 49
    AND (SELECT MAX(id) FROM `table`)

Compare actual run times andcuse the fastest.

like image 104
Bohemian Avatar answered Dec 02 '25 04:12

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!