MySQL provides the way to sort the result of any query in the ascending and descending order. MySQL provides a keyword “ORDER BY” to sort the data in the result set of the Select query. By default the ORDER BY keyword sorts the data in the ascending order. There are keywords ASC and DESC used with the ORDER BY clause for sorting the data in ascending and descending order respectively.
The basic query to sort the result set:
SELECT column1, column2, column3,…………., column from tableName ORDER BY columnM;
Here tableName is the table on which SELECT command is executes and columnM is the column name by which you want to sort the result.
For example:
We have a data of the company names along with their address and price of some server.
ID | Company | Address | Amount |
1 | HCL | NY | $7000 |
2 | Apple | Chicago | $2600 |
3 | IBM | INDIA | $3800 |
4 | Singapore | $15000 |
SELECT ID, Company, Address, Amount from company ORDER BY AMOUNT; OR SELECT ID, Company, Address, Amount from company ORDER BY AMOUNT ASC;
The result of above query is:
ID | Company | Address | Amount |
4 | Singapore | $15000 | |
1 | HCL | NY | $7000 |
3 | IBM | INDIA | $3800 |
2 | Apple | Chicago | $2600 |
SELECT ID, Company, Address, Amount from company ORDER BY company desc;
ID | Company | Address | Amount |
2 | Apple | Chicago | $2600 |
4 | Singapore | $15000 | |
1 | HCL | NY | $7000 |
3 | IBM | INDIA | $3800 |
You can also use ORDER BY or sorting for one or more columns, the basic syntax for the same is as:
SELECT column1, column2, .. , columnN FROM tableNameORDER BY column1, column2;
For example we have the data of company as:
ID | Company | Address | Amount |
2 | Apple | Chicago | $2600 |
4 | Singapore | $15000 | |
1 | HCL | Chicago | $7000 |
3 | IBM | INDIA | $3800 |
SELECT ID, Company, Address, Amount from company ORDER BY Address, company;
The resultant of this query is:
ID | Company | Address | Amount |
2 | Apple | Chicago | $2600 |
1 | HCL | Chicago | $7000 |
3 | IBM | INDIA | $3800 |
4 | Singapore | $15000 |