mysql  order by clause

the order By keyword is used to sort the result-set.

the MySQL order by statement is used for sorting records. the records can be sorted in ascending and descending orders.

the order by command - clause allows you to :

  • sort a result set by a single column or multiple column
  • sort a result set by different columns in ascending or descending order.

the order by keyword in MySQL sorts the records in ascending order by default.to sort the records in a descending order, you can use the desc keyword.

mysql  order by  syntax

            select    column_name1,   column_name2, ...

            from   table_name
                       
            order by  column_name1 [ asc | desc ], column_name2  [ asc | desc ], ...

the asc stands for ascending order and the desc stands for descending order .


demo database table

below is a selection from the "user" table:

useridfirstnamelastnamemobilenocity
1sandeepkumar9549293245india
2ramkumar9549293212usa
3shyamdhaka2323234545jaipur
4ankitnehra3423567845uae
5radhakumari2323121212jaipur

MySQL order by [asc] Example (order ascending)

the following mysql statement selects all the users from the user table, sorted by the "firstname" column :

by default, the order by clause sorts the result-set in ascending order .

 enter password:******
 mysql> use userinformation;
 database changed
               
 mysql>  select      *          from        user 
      
               order by    firstname ;
useridfirstnamelastnamemobilenocity
4ankitnehra3423567845uae
5radhakumari2323121212jaipur
2ramkumar9549293212usa
1sandeepkumar9549293245india
3shyamdhaka2323234545jaipur

MySQL order by [desc] example (order descending)

the following mysql statement selects all the users from the user table, sorted descending by the "city" column :

 
        mysql> select      *          from        user 
      
               order by    city  desc;
useridfirstnamelastnamemobilenocity
2ramkumar9549293212usa
4ankitnehra3423567845uae
5radhakumari2323121212jaipur
3shyamdhaka2323234545jaipur
1sandeepkumar9549293245india

examples - order by ascending and descending in MySQL

if you want to sort the names by 'lastname' in descending order and 'firstname' in ascending order. you specify both desc and asc in corresponding column :

 
  mysql> select      lastname, firstname          
               
               from         user 
      
               order by    lastname   desc,
               
                                firstname    asc ;
lastnamefirstname
nehraankit
kumariradha
kumarram
kumarsandeep
dhakashyam

note :- In the above query, the order by clause sorts the result set by 'lastname' in descending order first, and then sorts the sorted result-set by 'firstname' in ascending order to produce the final result set.