The order BY statement is used to sort the result set.
ORDER by statement
The order BY statement is used to sort the result set based on the specified column.
The order BY statement sorts records by default in ascending order.
If you want to sort records in descending order, you can use the DESC keyword.
The original table (used in the example):
Orders table:
| Company
OrderNumber |
Ibm |
3532 |
W3school |
2356 |
Apple |
4698 |
W3school |
6953 |
Example 1
Show company name in alphabetical order:
ORDER BY Company
Results:
| Company
OrderNumber |
Apple |
4698 |
Ibm |
3532 |
W3school |
6953 |
W3school |
2356 |
Example 2
Displays the company name in alphabetical order and displays the order number (OrderNumber) in numerical order:
ORDER BY Company, OrderNumber
Results:
| Company
OrderNumber |
Apple |
4698 |
Ibm |
3532 |
W3school |
2356 |
W3school |
6953 |
Example 3
Show company name in reverse alphabetical order:
ORDER BY Company DESC
Results:
| Company
OrderNumber |
W3school |
6953 |
W3school |
2356 |
Ibm |
3532 |
Apple |
4698 |
Example 4
Displays the company name in reverse alphabetical order and displays the sequential number in numerical order:
ORDER BY Company DESC, OrderNumber ASC
Results:
| Company
OrderNumber |
W3school |
2356 |
W3school |
6953 |
Ibm |
3532 |
Apple |
4698 |
Note: There are two equal company names (W3school) in the results above. Only this time, when there is the same value in the first column, the second column is in ascending order. This is the case if some of the values in the first column are nulls.
The SQL Order by clause is detailed