The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
SELECT column1, column2, ... FROM table_name ORDER BY column1, column2, ... ASC|DESC;
Below is a selection from the Customers table used in the examples:
Customers Table:
| CustomerID | CustomerName | Country |
|---|---|---|
| 1 | Alfreds Futterkiste | Germany |
| 2 | Ana Trujillo Emparedados | Mexico |
| 3 | Antonio Moreno Taquería | Mexico |
| 4 | Around the Horn | UK |
| 5 | Berglunds snabbköp | Sweden |
The following SQL statement selects all customers from the Customers table, sorted by the Country column.
SELECT * FROM Customers ORDER BY Country;
This is equivalent to ORDER BY Country ASC.
The following SQL statement selects all customers from the Customers table, sorted in descending order by the Country column.
SELECT * FROM Customers ORDER BY Country DESC;
You can also sort by multiple columns. The following SQL statement selects all customers, sorted by Country and then by CustomerName.
This means it will sort by Country, but if some rows have the same Country, it will sort them by CustomerName.
SELECT * FROM Customers ORDER BY Country, CustomerName;
You can also specify different sort orders for different columns.
SELECT * FROM Customers ORDER BY Country ASC, CustomerName DESC;