Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order by column if equal, order by another

Tags:

sql

Really I don't know how to say it as question, but with example it will be clear to everyone, I have data retrieved from MYSQL database sorted by one of columns , my question if one of those values in this column is equal, I need to use another column to set who is show first.

col1 - col2
10 - 100
20 - 120
20 - 140
30 - 90

see here value 20 mentioned twice so I need to show the 20 with 140 before the 20 with 120 using MYSQL Query.

like image 473
OsaMa Hasan Avatar asked Oct 08 '12 13:10

OsaMa Hasan


People also ask

How does ORDER BY clause works if two values are equal?

If the values are the same in the column used in the order by, the results will be random.

Can we use ORDER BY for 2 columns?

You can also ORDER BY two or more columns, which creates a nested sort . The default is still ascending, and the column that is listed first in the ORDER BY clause takes precedence. The following query and Figure 3 and the corresponding query results show nested sorts.

Can we use ORDER BY and GROUP BY in same query?

Using Group By and Order By Together When combining the Group By and Order By clauses, it is important to bear in mind that, in terms of placement within a SELECT statement: The GROUP BY clause is placed after the WHERE clause. The GROUP BY clause is placed before the ORDER BY clause.

Can you use ORDER BY on a column that is not one of the column in select statement?

Yes, you can order by a field(s)even if it is not your in your select statement but exists in your table.


1 Answers

SELECT
    *
FROM
    MyTable
ORDER BY 
    Col1,
    Col2 DESC
like image 80
Tobsey Avatar answered Sep 19 '22 19:09

Tobsey