Curriculum
Course: SQL
Login

Curriculum

SQL

SQL References

0/80

MySQL Functions

0/139

SQL Server Functions

0/84

SQL Quick Ref

0/1
Text lesson

SQL ORDER BY

The SQL ORDER BY

The ORDER BY clause is employed to arrange the result-set either in ascending or descending order.

Example

Arrange the products based on their prices.

SELECT * FROM Products
ORDER BY Price;

Syntax

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

Demo Database

Here is a portion of the Products table utilized in the examples:

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 ORDER BY keyword arranges the records in ascending order. To sort the records in descending order, utilize the DESC keyword.

Example

Arrange the products in descending order based on their prices.

SELECT * FROM Products
ORDER BY Price DESC;

Order Alphabetically

For string values, the ORDER BY keyword will arrange them alphabetically.

Example

Arrange the products alphabetically based on their ProductName.

SELECT * FROM Products
ORDER BY ProductName; 

Alphabetically DESC

To sort the table in reverse alphabetical order, employ the DESC keyword.

Example

Arrange the products by ProductName in reverse alphabetical order.

SELECT * FROM Products
ORDER BY ProductName DESC

ORDER BY Several Columns

The following SQL statement retrieves all customers from the “Customers” table, sorted first by the “Country” column and then by the “CustomerName” column. This arrangement ensures that rows are ordered by Country, and in cases where some rows share the same Country, they are further ordered by CustomerName.

Example

SELECT * FROM Customers
ORDER BY Country, CustomerName; 

Using Both ASC and DESC

The following SQL statement retrieves all customers from the “Customers” table, sorted in ascending order by the “Country” column and in descending order by the “CustomerName” column.

Example

SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC