Introduction
The ORDER BY clause is used to sort the result-set of a SELECT statement. This clause lets you specify one or more columns to sort by, and can optionally specify the sort order (ascending or descending).
Syntax
The basic syntax is as follows:
SELECT column1, column2, ...
FROM table_name
ORDER BY column_name [ASC | DESC];
Sorting by a Single Column
To sort by a single column in ascending order (default), use the following:
SELECT *
FROM Customers
ORDER BY LastName;
Example Output
CustomerID | City | Country
--------------|-------------|---------
1 | Austin | USA
2 | Lyon | France
3 | Houston | USA
4 | Osaka | Japan
5 | Paris | France
Sorting by Multiple Columns
To sort by multiple columns, list them separated by commas in the ORDER BY clause. The sorting will proceed from left to right. If the first column has the same value, the second column will be used to break the tie.
SELECT *
FROM Products
ORDER BY Category, UnitPrice DESC;
Sorting in Descending Order
To sort in descending order, use the DESC keyword after the column name.
SELECT *
FROM Employees
ORDER BY Salary DESC;
Null Values
The behavior of ORDER BY with NULL values can vary depending on the database system. Typically, NULL values are treated as the lowest possible values, which results in them appearing first or last in the sorted result. This behavior is database-specific.