SQL ORDER BY Keyword
What is the ORDER BY Keyword?
The ORDER BY keyword is used to sort the result set in ascending (ASC) or descending (DESC) order.
Example: Sort by Price
Sort the products by their price:
SELECT * FROM Products
ORDER BY Price;
Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Demo Database
Below is a selection from the “Products” table used in the examples:
| ProductID | ProductName | Price |
|---|---|---|
| 1 | Chais | 18 |
| 2 | Chang | 19 |
Sorting in Descending Order
To sort records in descending order, use the DESC keyword:
SELECT * FROM Products
ORDER BY Price DESC;
Sorting Alphabetically
Sort the products alphabetically by their name:
SELECT * FROM Products
ORDER BY ProductName;
To sort in reverse alphabetical order, add the DESC keyword:
SELECT * FROM Products
ORDER BY ProductName DESC;
Sorting by Multiple Columns
To sort by multiple columns, specify them separated by commas. For example:
SELECT * FROM Customers
ORDER BY Country, CustomerName;
Use different sorting orders for each column:
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
