loading

SQL Order By

The SQL ORDER BY

To arrange the result-set in either ascending or descending order, use the ORDER BY keyword.

Example

Sort the products by price:

				
					SELECT * FROM Products
ORDER BY Price;
				
			

Syntax

SELECT column1, column2, …

FROM table_name

ORDER BY column1, column2, … ASC|DESC;

Demo Database

ProductID ProductName SupplierID CategoryID Unit Price
1 Chais 1 1 10 boxes x 20 bags 18
2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 22
5 Chef Anton's Gumbo Mix 2 2 36 boxes 21.35

DESC

By default, the records are sorted in ascending order using the ORDER BY keyword. Use the DESC keyword to sort the records in descending order.

Example

Sort the products from highest to lowest price:

				
					SELECT * FROM Products
ORDER BY Price DESC;
				
			

Order Alphabetically

The ORDER BY keyword will sort string items alphabetically:

Example

Sort the products alphabetically by ProductName:

				
					SELECT * FROM Products
ORDER BY ProductName;
				
			

Alphabetically DESC

Use the DESC keyword to sort the table in reverse alphabetical order:

Example

Sort the products by ProductName in reverse order:

				
					SELECT * FROM Products
ORDER BY ProductName DESC;
				
			

ORDER BY Several Columns

Sorted by “Country” and “CustomerName” columns, the “Customers” table contains all of the customers that are selected by the SQL query that follows. This indicates that rows are sorted by CustomerName if several rows have the same Country, otherwise they are sorted by Country:

Example

				
					SELECT * FROM Customers
ORDER BY Country, CustomerName;
				
			

Using Both ASC and DESC

With the “Country” column ordered ascending and the “CustomerName” column sorted descending, the SQL statement that follows chooses every customer from the “Customers” table:

Example

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

SQL Order By

Or copy link

Explore Topic