Select the last n rows from a MySQL table

I needed to figure out how to select the last four rows of a database table without reversing the order of the rows. After a little digging, I got to this point:

SELECT * 
FROM (
    SELECT * 
    FROM table_name 
    WHERE whatever 
    ORDER BY date DESC LIMIT 4
) AS tbl 
ORDER BY tbl.date ASC;

So, as long as you have something to order by, you can reverse and re-reverse the order, and it will come out right in the end.

Note: Originally written September 2, 2010

About Scott Allen

Scott Allen is a web developer from Indianapolis, Indiana. He has been working with HTML, CSS, PHP, & MySQL since the late '90s, and has extensive experience in database design and development, server-side scripting, content management, and front-end user experience, especially in the creation of educational content. Connect with Scott on Twitter (preferably), or Facebook or Google+ (if you aren't in a hurry).
This entry was posted in Code, Tech and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *