SQL ORDER BY Clause
- Previous Page SQL AND & OR
- Next Page SQL insert
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 is used to sort the records in ascending order by default.
If you want to sort the records in descending order, you can use the DESC keyword.
Original Table (used in examples):
Orders Table:
Company | OrderNumber |
---|---|
IBM | 3532 |
W3School | 2356 |
Apple | 4698 |
W3School | 6953 |
Example 1
Display company names in alphabetical order:
SELECT Company, OrderNumber FROM Orders ORDER BY Company
Result:
Company | OrderNumber |
---|---|
Apple | 4698 |
IBM | 3532 |
W3School | 6953 |
W3School | 2356 |
Example 2
Display company names (Company) in alphabetical order and sequence numbers (OrderNumber) in numerical order:
SELECT Company, OrderNumber FROM Orders ORDER BY Company, OrderNumber
Result:
Company | OrderNumber |
---|---|
Apple | 4698 |
IBM | 3532 |
W3School | 2356 |
W3School | 6953 |
Example 3
Display company names in reverse alphabetical order:
SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC
Result:
Company | OrderNumber |
---|---|
W3School | 6953 |
W3School | 2356 |
IBM | 3532 |
Apple | 4698 |
Example 4
Display company names in reverse alphabetical order and sequence numbers in numerical order:
SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC, OrderNumber ASC
Result:
Company | OrderNumber |
---|---|
W3School | 2356 |
W3School | 6953 |
IBM | 3532 |
Apple | 4698 |
Note:There are two identical company names (W3School) in the above results. Only this time, when the values in the first column are the same, the second column is sorted in ascending order. If there are some nulls in the first column, the situation is also the same.
- Previous Page SQL AND & OR
- Next Page SQL insert