Subsections

1.4.12.6 ORDER BY

The ORDER BY keyword is used to sort the result.

1.4.12.6.1 Sort the Rows

The ORDER BY clause is used to sort the rows.

Orders:

+-------------+-------------+
| Company     | OrderNumber |
+-------------+-------------+
| 'Asda'      | 5678        |
| 'Morrisons' | 1234        |
| 'Tesco'     | 2345        |
| 'Morrisons' | 7654        |
+-------------+-------------+

To display the companies in alphabetical order:

SELECT Company, OrderNumber FROM Orders ORDER BY Company

Result:

+-------------+-------------+
| Company     | OrderNumber |
+-------------+-------------+
| 'Asda'      | 5678        |
| 'Morrisons' | 1234        |
| 'Morrisons' | 7654        |
| 'Tesco'     | 2345        |
+-------------+-------------+

Example

To display the companies in alphabetical order AND the order numbers in numerical order:

SELECT Company, OrderNumber FROM Orders ORDER BY Company, OrderNumber

Result:

+-------------+-------------+
| Company     | OrderNumber |
+-------------+-------------+
| 'Asda'      | 5678        |
| 'Morrisons' | 1234        |
| 'Morrisons' | 7654        |
| 'Tesco'     | 2345        |
+-------------+-------------+

Example

To display the companies in reverse alphabetical order:

SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC

Result:

+-------------+-------------+
| Company     | OrderNumber |
+-------------+-------------+
| 'Tesco'     | 2345        |
| 'Morrisons' | 1234        |
| 'Morrisons' | 7654        |
| 'Asda'      | 5678        |
+-------------+-------------+

Example

To display the companies in alphabetical order AND the order numbers in reverse numerical order:

SELECT Company, OrderNumber FROM Orders ORDER BY Company ASC, OrderNumber DESC

Result:

+-------------+-------------+
| Company     | OrderNumber |
+-------------+-------------+
| 'Asda'      | 5678        |
| 'Morrisons' | 7654        |
| 'Morrisons' | 1234        |
| 'Tesco'     | 2345        |
+-------------+-------------+