Learn From - Interactive SQL



The SQL ORDER BY Keyword


The ORDER BY keyword sorts the data in the columns in the ascending order for one or more columns by default.

For sorting the data in the columns in descending order, we have to use the DESC keyword. This is only used as part of Select Statement to organise records based on one or more columns.

SQL ORDER BY Syntax


SELECT column_name1,column_name2..
FROM table_name
ORDER BY column_name1,column_name2.. ASC|DESC

SQL ORDER BY Example


Below is shown the "Customers" table:

CustomerID CustomerName EmailID Address City PostalCode Country
C001 Fredrick Johnson FJohnson@yahoo.com Berkeley Gardens 12 Brewery London WX1 6LT UK
C002 Mary Davidson Mary@gmail.com 35 King George Madrid 28023 Spain
C003 George Clooney George@hotmail.com Obere Str. 57 Berlin 12209 Germany
C004 David Louis David@mail.com 2743 Bering St. NewJersy 07019 USA
C005 Johnny Anderson Johnny@gmail.com 55 Grizzly Peak Rd. NewJersy 07019 USA
C006 Paul Henriot PaulHenriot@yahoo.com 59 rue de l'Abbaye Paris 51100 France
C007 Henry King Henry@mail.com 120 Hanover Sq. London WA1 1DP UK
C008 Robert John Robert@gmail.com 87 Polk St. Suite 5 San Francisco 94117 USA

Type or Copy the SQL into the Text Editor, click the "View Result" button, to see the result.

Retrieve all customers sorted in ascending order based on "Country" and the "CustomerName" columns.

SELECT * FROM Customers
ORDER BY Country,CustomerName;

Retrieve all customers sorted in descending order based on "Country" and the "CustomerName" columns.

SELECT * FROM Customers
ORDER BY Country Desc,CustomerName Desc;

Note: The descsending DESC keyword has to be given for each column, so that column is sorteed in descending order.

SQL in Text Editor: