Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding order by with offset and limit in mysql query

Tags:

mysql

I have a mysql query

SELECT * FROM lead LIMIT 5 OFFSET 0  

to select data from the table lead and limit the results to 5 with offset of 0. I would like to order the results by its id by desc, so the results will be populated as the last added data first.

I tried

SELECT * FROM lead LIMIT 5 OFFSET 0 order by id desc 

but it's not working. Please correct me where am wrong.

like image 919
Bala Avatar asked Nov 16 '11 09:11

Bala


People also ask

Can we use limit with ORDER BY in MySQL?

If you do LIMIT first and then ORDER BY, it will throw an error. ORDER BY must be first in the query.

How do you use limit and offset in query?

The limit option allows you to limit the number of rows returned from a query, while offset allows you to omit a specified number of rows before the beginning of the result set. Using both limit and offset skips both rows as well as limit the rows returned.

How do you use limit and ORDER BY together?

ORDER BY LIMIT is used to get rows from table in sorting order either in ascending or descending order and to limit rows in result-set. ORDER BY LIMIT is not supported in all databases. ORDER BY LIMIT works only in MySQL.

Does MySQL allow the use of ORDER BY and limit in the same query?

In MySQL, the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments that are offset and count. The value of both the parameters can be zero or positive integers.


1 Answers

You have to

select * from lead order by id desc LIMIT 5 OFFSET 0 

The manual ( http://dev.mysql.com/doc/refman/5.0/en/select.html ) describes that LIMIT is only allowed to appear after the ORDER BY.

like image 77
Dennis Avatar answered Oct 14 '22 11:10

Dennis