The ORDER BY clause is employed to arrange the result-set either in ascending or descending order.
Arrange the products based on their prices.
SELECT * FROM Products ORDER BY Price; |
SELECT column1, column2, ... |
Here is a portion of the Products table utilized in the examples:
ProductID |
ProductName |
SupplierID |
CategoryID |
Unit |
Price |
1 |
Chais |
1 |
1 |
10 boxes x 20 bags |
18 |
2 |
Chang |
1 |
1 |
24 – 12 oz bottles |
19 |
3 |
Aniseed Syrup |
1 |
2 |
12 – 550 ml bottles |
10 |
4 |
Chef Anton’s Cajun Seasoning |
2 |
2 |
48 – 6 oz jars |
22 |
5 |
Chef Anton’s Gumbo Mix |
2 |
2 |
36 boxes |
21.35 |
By default, the ORDER BY keyword arranges the records in ascending order. To sort the records in descending order, utilize the DESC keyword.
Arrange the products in descending order based on their prices.
SELECT * FROM Products ORDER BY Price DESC; |
For string values, the ORDER BY keyword will arrange them alphabetically.
Arrange the products alphabetically based on their ProductName.
SELECT * FROM Products ORDER BY ProductName; |
To sort the table in reverse alphabetical order, employ the DESC keyword.
Arrange the products by ProductName in reverse alphabetical order.
SELECT * FROM Products ORDER BY ProductName DESC; |
The following SQL statement retrieves all customers from the “Customers” table, sorted first by the “Country” column and then by the “CustomerName” column. This arrangement ensures that rows are ordered by Country, and in cases where some rows share the same Country, they are further ordered by CustomerName.
SELECT * FROM Customers ORDER BY Country, CustomerName; |
The following SQL statement retrieves all customers from the “Customers” table, sorted in ascending order by the “Country” column and in descending order by the “CustomerName” column.
SELECT * FROM Customers ORDER BY Country ASC, CustomerName DESC; |