Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL limit from descending order

Tags:

mysql

Is it available to write a query to use same "LIMIT (from), (count)", but get result in backwards?

In example if I have 8 rows in the table and I want to get 5 rows in two steps I would: first step query:

select * from table limit 0, 5 

first step result:

first 5 rows; 

second step query:

select * from table limit 5, 5 

second step result:

last 3 rows; 

But I want to get it vice versa. I mean from the first step I want last 3 rows and from the second I want 5 first rows. Thank you for your answer

like image 398
faya Avatar asked Apr 25 '10 16:04

faya


People also ask

What is desc LIMIT in MySQL?

Description. The MySQL SELECT LIMIT statement is used to retrieve records from one or more tables in MySQL and limit the number of records returned based on a limit value.

How do I SELECT descending order in MySQL?

The MySQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How will you LIMIT a MySQL query to display only top 10 rows?

To select first 10 elements from a database using SQL ORDER BY clause with LIMIT 10. Insert some records in the table using insert command. Display all records from the table using select statement. Here is the alternate query to select first 10 elements.


2 Answers

No, you shouldn't do this. Without an ORDER BY clause you shouldn't rely on the order of the results being the same from query to query. It might work nicely during testing but the order is indeterminate and could break later. Use an order by.

SELECT * FROM table1 ORDER BY id LIMIT 5 

By the way, another way of getting the last 3 rows is to reverse the order and select the first three rows:

SELECT * FROM table1 ORDER BY id DESC LIMIT 3 

This will always work even if the number of rows in the result set isn't always 8.

like image 119
Mark Byers Avatar answered Oct 07 '22 11:10

Mark Byers


Let's say we have a table with a column time and you want the last 5 entries, but you want them returned to you in asc order, not desc, this is how you do it:

select * from ( select * from `table` order by `time` desc limit 5 ) t order by `time` asc 
like image 42
Dev Null Avatar answered Oct 07 '22 12:10

Dev Null