SQL ORDER BY

The SQL ORDER BY Keyword

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.


Syntax

SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

Demo Database

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

Example 1: Sort Ascending (Default)

The following SQL statement selects all customers from the Customers table, sorted by the Country column.

ORDER BY ASC Example

SELECT * FROM Customers
ORDER BY Country;

This is equivalent to ORDER BY Country ASC.


Example 2: Sort Descending

The following SQL statement selects all customers from the Customers table, sorted in descending order by the Country column.

ORDER BY DESC Example

SELECT * FROM Customers
ORDER BY Country DESC;

Example 3: Sorting by Multiple Columns

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.

ORDER BY Multiple Columns Example

SELECT * FROM Customers
ORDER BY Country, CustomerName;

You can also specify different sort orders for different columns.

ORDER BY Multiple Columns with Mixed Order

SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;