ORDER BY

The SQL ORDER BY Keyword

ORDER BY sorts the result set in ascending (ASC, the default) or descending (DESC) order.

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

Note: Without ORDER BY, the order of rows is not guaranteed, even if it looks stable today.

Ascending

Example

Sort products by price, cheapest first:

SELECT ProductName, Price FROM Products
ORDER BY Price;

Result: 6 rows

ProductNamePrice
Dark Chocolate3.49
Green Tea 100 bags6.75
Almonds 500g8.25
Olive Oil 1L9.99
Basmati Rice 5kg12.5
Espresso Beans 1kg18

DESC

Example

Sort products by price, most expensive first:

SELECT ProductName, Price FROM Products
ORDER BY Price DESC;

Result: 6 rows

ProductNamePrice
Espresso Beans 1kg18
Basmati Rice 5kg12.5
Olive Oil 1L9.99
Almonds 500g8.25
Green Tea 100 bags6.75
Dark Chocolate3.49

Order Alphabetically

Example

For text columns, ORDER BY sorts alphabetically:

SELECT CustomerName FROM Customers
ORDER BY CustomerName DESC;

Result: 8 rows

CustomerName
Harbor Lights
Golden Spoon
Fjord Supplies
Evergreen Grocers
Delta Mart
Cedar & Co
Blue Harbor Foods
Aarav Traders

ORDER BY Several Columns

Example

Sort by country, and within each country by customer name:

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

Result: 8 rows

CountryCustomerName
CanadaCedar & Co
IndiaDelta Mart
IndiaAarav Traders
NorwayFjord Supplies
SingaporeGolden Spoon
UKHarbor Lights
UKBlue Harbor Foods
USAEvergreen Grocers

Sorting and NULL

Databases disagree on where NULL goes: MySQL, SQL Server and SQLite put NULL first in ascending order; PostgreSQL and Oracle put it last. PostgreSQL and Oracle let you choose with NULLS FIRST / NULLS LAST.

Example

Golden Spoon (no city) appears first here:

SELECT CustomerName, City FROM Customers
ORDER BY City;

Result: 8 rows

CustomerNameCity
Golden SpoonNULL
Delta MartBengaluru
Blue Harbor FoodsLondon
Harbor LightsLondon
Aarav TradersMumbai
Evergreen GrocersNew York
Fjord SuppliesOslo
Cedar & CoToronto