Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL reverse order without DESC

Tags:

mysql

SELECT id FROM table LIMIT 8, 3

results in 8,9,10

but I need 10,9,8

How can you do this? If you add "ORDER BY id DESC" it gets 3,2,1

like image 622
Qiao Avatar asked Feb 20 '10 09:02

Qiao


People also ask

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 . You can use id or date as the field name.

How do I reverse the order of a query in SQL?

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

What is using Filesort in MySQL?

In MySQL, filesort is the catch-all algorithm for producing sorted results for ORDER-BY or GROUP-BY queries. MySQL has two algorithms for filesort, both the original and the modified algorithms are described in the user manual.

How do I sort by alphabetical order in MySQL?

Use the ORDER BY clause to sort the result set by one or more columns. Use the ASC option to sort the result set in ascending order and the DESC option to sort the result set in descending order.


1 Answers

Put your query in a subselect and then reverse the order in the outer select:

SELECT id from (
    SELECT id FROM table ORDER BY id LIMIT 8, 3
) AS T1 ORDER BY id DESC

Test data:

CREATE TABLE table1 (id INT NOT NULL);
INSERT INTO table1 (id) VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11);

SELECT id from (
    SELECT id FROM table1 ORDER BY id LIMIT 8, 3
) AS T1 ORDER BY id DESC

Result:

10
9
8

Note that the ORDER BY in the subquery is required otherwise the order is undefined. Thanks to Lasse for pointing this out!

like image 79
Mark Byers Avatar answered Oct 13 '22 21:10

Mark Byers