Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select rows in reverse order in MySQL?

Tags:

sql

mysql

How can I select rows in reverse order in MySQL?

For example, I have a table with 12 rows (fields: id,location), I want to select the 4th row before a row with id = 6. I.e., the wanted row will have id = 'not necessarily 2', but there is a condition - where table.location='some_location'.

What should the content of request to MySQL be like?


Here is a solution!

Some example (I checked drodil's suggestion):

mysql> select * from subscrs where id < 100000 order by id desc limit 4;
+-------+--------+-----------+-------+
| uid   | subscr | event     | id    |
+-------+--------+-----------+-------+
|  5307 |   5123 | feed_news | 99999 |
| 25985 |   5211 | feed_news | 99998 |
| 15123 |    130 | feed_news | 99997 |
| 28368 |  19497 | feed_news | 99996 |
+-------+--------+-----------+-------+
4 rows in set (0.00 sec)
like image 719
Yura Borisenko Avatar asked Mar 06 '12 11:03

Yura Borisenko


People also ask

How do you reverse a row in SQL?

The SQL ORDER BY Keyword The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do I change the order of rows in MySQL?

To sort the rows in the result set, you add the ORDER BY clause to the SELECT statement. In this syntax, you specify the one or more columns that you want to sort after the ORDER BY clause. The ASC stands for ascending and the DESC stands for descending.

How do I reverse a query in MySQL?

REVERSE() Function in MySQL This function could be used to reverse a string and find the result. The REVERSE() function takes input parameter as string and results the reverse order of that string. The parameter string is mandatory, It is the string that will be reversed.

How do I Reverse Print Order in MySQL?

By default, MySQL will show results in ascending order. If you want to show them in reverse order, use ORDER BY field_name DESC .


2 Answers

Or you could do it without caring about the deleted results. Just get the fourth before the given id (6) by:

SELECT * FROM SomeTable WHERE id < 6 ORDER BY id DESC LIMIT 4,1
like image 168
drodil Avatar answered Oct 13 '22 15:10

drodil


Please add ORDER BY id DESC in the last of your query to fetch the data from last to first.

OR

For assenting order, you can simply add ORDER BY id ASC.

like image 32
Ian Leaf Fraud Avatar answered Oct 13 '22 14:10

Ian Leaf Fraud