Using SQL ORDER BY keyword for sorting result set in MYSQL

No comments
ORDER BY keyword is used for sorting purpose of the result set in MySQl. Using order by we can specify the sorting order for the result set based on column values. By default sorting order is ascending but we can use DESC if we want to sort the result set in descending order.

SQL syntax and example for using ORDER BY keyword in MySql -

 SELECT * FROM CUSTOMER ORDER BY AGE;

 +----+--------+---------+------+-----------+
| ID | FNAME  | LNAME   | AGE  | COUNTRY   |
+----+--------+---------+------+-----------+
|  1 | AKSHAY | KUMAR   |   12 | INDIA     |
|  5 | JESSIE | JACKSON |   22 | CANADA    |
|  4 | JESSIE | PINKMAN |   25 | AUSTRALIA |
|  2 | JONTY  | RHODES  |   40 | CHINA     |
|  3 | JOHNY  | DEPP    |   45 | INDIA     |
+----+--------+---------+------+-----------+
5 rows in set (0.02 sec)
Above result set is in ascending order of AGE because we have not specified any order.
We can get the result set in descending order also by specifying DESC keyword.

  SELECT * FROM CUSTOMER ORDER BY AGE DESC;

 +----+--------+---------+------+-----------+
| ID | FNAME  | LNAME   | AGE  | COUNTRY   |
+----+--------+---------+------+-----------+
|  3 | JOHNY  | DEPP    |   45 | INDIA     |
|  2 | JONTY  | RHODES  |   40 | CHINA     |
|  4 | JESSIE | PINKMAN |   25 | AUSTRALIA |
|  5 | JESSIE | JACKSON |   22 | CANADA    |
|  1 | AKSHAY | KUMAR   |   12 | INDIA     |
+----+--------+---------+------+-----------+
5 rows in set (0.00 sec)
Now the given result set is in descending order of age of the customers.

No comments :

Post a Comment