Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Order by desc" in reverse order?

Welcome,

I'm wondering is it possible to reverse returned data in sorting "order by desc" but i want that data in reverse order.

For example, i got table with values

ID
1
2
3
4

And i do

Order by ID ASC LIMIT 3 I got

1
2
3

When i do Order by ID DESC limit 3 i get

4
3
2

I would like to have

3
2
1

So i would like to order by ASC but revers results. I was always doing this in PHP side using array_reverse, but today i want ask You. Maybye i'm wrong and i can do this just in Mysql. Regards

like image 857
marc Avatar asked Sep 05 '10 17:09

marc


People also ask

How do I reverse an order in SQL?

ASCending and DESCending Order Direction By default things are sorted by ascending order. You can choose to reverse that order by specifying DESC, for descending. Similarly if you'd like to specify that you want ASCending you use ASC.

Is ORDER BY DESC or ASC?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.

Is ORDER BY DESC by default?

You can use the ASC and DESC keywords to specify ascending (smallest value first) or descending (largest value first) order. The default order is ascending.

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

SELECT * 
FROM (
  SELECT ... 
  FROM ... 
  ORDER BY ID ASC 
  LIMIT 3
) AS sq 
ORDER BY ID DESC

Think of it as working in two steps. First it executes the inner query: selects 3 records with lowest IDs. Then in the outer query it sorts them in descending order.

like image 173
Mchl Avatar answered Oct 12 '22 09:10

Mchl


You can fetch the first three rows using a subquery and then reverse the order of these rows in an outer query:

SELECT *
FROM
(
    SELECT *
    FROM yourtable
    ORDER BY ID
    LIMIT 3
) T1
ORDER BY ID DESC
like image 37
Mark Byers Avatar answered Oct 12 '22 10:10

Mark Byers