SQL ORDER BY clause
The SQL ORDER BY clause is used to sort the result-set by one or more columns. It is used when you want your result from database to set in a particular order (by default, the records are sorted in ascending order). The syntax is:
SELECT column_name1, column_name2 FROM table_name ORDER BY column_name1 ASC|DESC, column_name2 ASC|DESC;
We will use the Employees table to illustrate the SQL ORDER BY clause:
+----------------+-----------+-----------+-----------+
| employeeNumber | lastName | firstName | extension |
+----------------+-----------+-----------+-----------+
| 1002 | Murphy | Diane | x5800 |
| 1056 | Patterson | Mary | x4611 |
| 1076 | Firrelli | Jeff | x9273 |
| 1088 | Patterson | William | x4871 |
| 1102 | Bondur | Gerard | x5408 |
| 1143 | Bow | Anthony | x5428 |
| 1165 | Jennings | Leslie | x3291 |
| 1166 | Thompson | Leslie | x4065 |
| 1188 | Firrelli | Julie | x2173 |
| 1216 | Patterson | Steve | x4334 |
| 1286 | Tseng | Foon Yue | x2248 |
| 1323 | Vanauf | George | x4102 |
| 1337 | Bondur | Loui | x6493 |
| 1370 | Hernandez | Gerard | x2028 |
| 1401 | Castillo | Pamela | x2759 |
| 1501 | Bott | Larry | x2311 |
| 1504 | Jones | Barry | x102 |
| 1611 | Fixter | Andy | x101 |
| 1612 | Marsh | Peter | x102 |
| 1619 | King | Tom | x103 |
| 1621 | Nishi | Mami | x101 |
| 1625 | Kato | Yoshimi | x102 |
| 1702 | Gerard | Martin | x2312 |
+----------------+-----------+-----------+-----------+
If you want to sort the Employees table data by the First Name column, you can use the following command:
SELECT * FROM employees ORDER BY firstName;
This would produce the following result:
+----------------+-----------+-----------+-----------+
| employeeNumber | lastName | firstName | extension |
+----------------+-----------+-----------+-----------+
| 1611 | Fixter | Andy | x101 |
| 1143 | Bow | Anthony | x5428 |
| 1504 | Jones | Barry | x102 |
| 1002 | Murphy | Diane | x5800 |
| 1286 | Tseng | Foon Yue | x2248 |
| 1323 | Vanauf | George | x4102 |
| 1102 | Bondur | Gerard | x5408 |
| 1370 | Hernandez | Gerard | x2028 |
| 1076 | Firrelli | Jeff | x9273 |
| 1188 | Firrelli | Julie | x2173 |
| 1501 | Bott | Larry | x2311 |
| 1165 | Jennings | Leslie | x3291 |
| 1166 | Thompson | Leslie | x4065 |
| 1337 | Bondur | Loui | x6493 |
| 1621 | Nishi | Mami | x101 |
| 1702 | Gerard | Martin | x2312 |
| 1056 | Patterson | Mary | x4611 |
| 1401 | Castillo | Pamela | x2759 |
| 1612 | Marsh | Peter | x102 |
| 1216 | Patterson | Steve | x4334 |
| 1619 | King | Tom | x103 |
| 1088 | Patterson | William | x4871 |
| 1625 | Kato | Yoshimi | x102 |
+----------------+-----------+-----------+-----------+