Select last N rows from MySQL

nanobash picture nanobash · Aug 25, 2012 · Viewed 252.6k times · Source

I want to select last 50 rows from MySQL database within column named id which is primary key. Goal is that the rows should be sorted by id in ASC order, that’s why this query isn’t working

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

Also it’s remarkable that rows could be manipulated (deleted) and that’s why following query isn’t working either

SELECT 
    *
FROM
    `table`
WHERE
    id > ((SELECT 
            MAX(id)
        FROM
            chat) - 50)
ORDER BY id ASC;

Question: How is it possible to retrieve last N rows from MySQL database that can be manipulated and be in ASC order ?

Answer

newfurniturey picture newfurniturey · Aug 25, 2012

You can do it with a sub-query:

SELECT * FROM (
    SELECT * FROM table ORDER BY id DESC LIMIT 50
) sub
ORDER BY id ASC

This will select the last 50 rows from table, and then order them in ascending order.