Skip to content

The SQL ORDER BY Keyword

ORDER BY sorts the rows of a result. Without it, a database returns rows in whatever order is quickest for it, which can change from one run to the next. When the order matters, say so.

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

ASC sorts from lowest to highest and is the default, so it is usually left out. DESC sorts from highest to lowest. Text sorts alphabetically, numbers by size and dates from earliest to latest.

The examples use the Productions table from the example database.

To list the productions from the largest budget down:

SELECT Title, Budget
FROM Productions
ORDER BY Budget DESC;
Title Budget
The Lantern Keepers 18,500,000
Six Bells 11,000,000
Quarry Lane 7,200,000
Saltmarsh 3,900,000
Fennick’s Return 850,000

List more than one column and the database sorts on the first, then uses the next to break ties. Here the productions are grouped by country, and the three UK productions, which tie on country, are put in alphabetical order:

SELECT Title, Country
FROM Productions
ORDER BY Country, Title;
Title Country
Fennick’s Return Canada
Saltmarsh Ireland
Quarry Lane UK
Six Bells UK
The Lantern Keepers UK

Each column takes its own direction. This sorts the countries A to Z, and within each country puts the biggest budget first:

SELECT Title, Country, Budget
FROM Productions
ORDER BY Country ASC, Budget DESC;
Title Country Budget
Fennick’s Return Canada 850,000
Saltmarsh Ireland 3,900,000
The Lantern Keepers UK 18,500,000
Six Bells UK 11,000,000
Quarry Lane UK 7,200,000