Home » MySQL

MySQL Tutorial: Fetch last 10 rows without reversing order

5 January 2010 2 Comments

Here’s the quickest way to sort data in MySQL after retrieving the last 10 entries with the LIMIT and ORDER BY DESC commands. If you simply do a ORDER BY DESC LIMIT 10, this will return the last 10 results in reverse order (newest first). Adding an inline SELECT command will sort the results after retrieving the last 10 items. (oldest first)

SQL Command

$sql = "SELECT * FROM (SELECT * FROM [TABLE] WHERE ORDER BY modified_date DESC LIMIT 10) AS tbl ORDER BY tbl.modified_date"

This will retrieve the last 10 rows while sorting by date chronologically. I used this SQL command for the graphing API I was using (LibChart). This allowed my graph to display the most current data on the right side as opposed to the left.

2 Comments »

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.

*