Friday, March 30, 2012

Using Limit in MySQL

There are times when you would like to limit the results coming back on a query to certain amount of records.  For instance, if I need to see the last 10 records in a table, I could use the following query:

SELECT * FROM TABLE ORDER BY rownum DESC LIMIT 10;


The previous line would order the records in the table by the row number is descending order and return only the last 10 in the table.  Simple enough.

Now, let's say that we want to get back the 11th-20th records.  We can use LIMIT for this purpose as well.  This would be the query for that:

SELECT * FROM TABLE ORDER BY rownum DESC LIMIT 10,10;


So, the LIMIT keyword can be very useful in getting subsets back for queries.


No comments:

Post a Comment