Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reverse the default ordering in MySQL?

In MySQL, when you execute a select SQL statement, there is a default ordering if you don't include a sorting clause. How can I reverse the default ordering? Just add DESC?

like image 507
Steven Avatar asked Nov 27 '09 06:11

Steven


People also ask

How do I reverse sort 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.

What is the default sort done in MySQL when you ORDER BY clause?

In SQL ORDER BY clause, we need to define ascending or descending order in which result needs to be sorted. By default, SQL Server sorts out results using ORDER BY clause in ascending order.

What is the default ordering of rows returned from a select query?

When you issue a SELECT , the rows often get returned in the same order they were inserted in the table. You can change the order of the rows by adding an ORDER BY clause at the end of your query, with a column name after. By default, the ordering will be in "ascending order", from lowest value to highest value.


2 Answers

You can set a counter in your result fields and sort using it:

SELECT *, @counter := @counter + 1 AS 'counter' FROM tableName, (SELECT @counter := 0) r ORDER BY counter DESC

I think it will work as you want.

like image 180
Mohsen Haeri Avatar answered Oct 07 '22 11:10

Mohsen Haeri


If you want the data to come out consistently ordered, you have to use ORDER BY followed by the column(s) you want to order the query by. ASC is the default, so you don't need to specify it. IE:

ORDER BY your_column

...is the equivalent to:

ORDER BY your_column ASC

ASC/DESC is on a per column basis. For example:

ORDER BY first_column, second_column DESC

...means that the query will sort the resultset as a combination using the first_column in ascending order, second_column in descending order.

like image 27
OMG Ponies Avatar answered Oct 07 '22 11:10

OMG Ponies