This SQL tutorial focuses on the MySQL ORDER BY clause, and provides explanations, examples and exercises. For this lesson exercises use this link.

The order of records retrieved by a query is undefined, to specify the order in which rows are displayed, you can use the MySQL ORDER BY clause. This tutorial explains how to sort the query result set in an ascending and descending order, and also how to sort by multiple columns.


The ORDER BY clause

ORDER BY

Sort the results in ascending and descending order

The MySQL ORDER BY clause is used to sort the query result set, based on a certain column:

ORDER BY column_name

For example, the following MySQL example sorts the result set by price (in ascending order, from the lowest to the highest):

SELECT bookID, bookName, bookPrice
FROM products
ORDER BY bookPrice

To reverse the order in which rows are displayed, use the keyword DESC after the column name in the MySQL ORDER BY clause:

SELECT bookID, bookName, bookPrice
FROM products
ORDER BY bookPrice DESC

Sort by multiple columns

You can sort the query result set by more than one column. In the ORDER BY clause, specify the columns and separate them using commas.

This MySQL example sorts the result set by author name and then by price:

SELECT bookName, bookPrice 
FROM products
ORDER BY Author, bookPrice

This MySQL example sorts the result set by author name in descending order and then by bookPrice:

SELECT bookName , bookPrice
FROM products
ORDER BY Author DESC, bookPrice