'hyphen in MySQL order by clause

I have a MySQL query with this line

ORDER BY -order_line_groups.sequence DESC, order_line_groups.id;

I'm trying to find out what the hyphen is for just after the order by. I have tried executing with and without it but it does not seem to make a difference. I have also looked at it with explain and cant find anything different.

I was not able to find any MySQL documentation to help. I did find this: https://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html where the hyphen is listed under "You use ORDER BY with an expression that includes terms other than the key column name:"

It does not give much info. Can someone explain what this does or point me towards some docs?

Thank you.



Solution 1:[1]

you are negating the value of column 'sequence' and using it in order by ..

order by -(number)

ordering by negation of a number.

Solution 2:[2]

In Mysql, you can almost any expression to determine how the data is sorted. If you do the following example:

order by (order_line_groups.sequence*order_line_groups.id)

It would calculate the value of sequence*id first. Then, it would sort the table using those calculated values.

Adding the hyphen to the column you're sorting by basically does this.

order by (order_line_groups.sequence*-1)

Essentially, you'll be sorting in descending order.

However, you actually sort that expression descending.

order by (order_line_groups.sequence*-1) DESC

It would take the descending order sort and reverse it so you have an ascending order sort.

I would recommend that you remove the hyphen and switch DESC to ASC so no one else gets confused.

Solution 3:[3]

Although I am late,But let me share ordering by hypen,number and alphabats in your data,

SELECT column FROM TABLE
 ORDER BY (column = '0') ASC, (column+0 > 0) DESC, column+0 ASC, column ASC

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Trenton Trama
Solution 3 Mohsin Khan