Site icon TestingDocs.com

MySQL SELECT ORDER BY clause

Overview

In this tutorial, we will learn MySQL SELECT ORDER BY clause with examples. By default the MySQL Server returns output rows in no specific order. We can use the ORDER BY clause when we require the output rows to be displayed in a specific order.

We can specify explicitly whether to sort a column in Ascending or Descending order by using the ASC or DESC keywords after the column names in the ORDER BY clause.

ORDER BY clause

SELECT [DISTINCT] columns_in_result
FROM table_name(s)
WHERE condition(s)
ORDER BY  column_name sort_order [ASC | DESC] ;

ASC

The default sort order of the ORDER BY clause is ascending order(ASC). In ascending order the lowest value comes first.

DESC

We can specify explicitly to sort a column in descending order by using the keyword DESC. In descending order the highest value comes first.

Example

Let’s see an example of the ORDER BY clause. We will use the Country database table in the world MySQL database.

Sort single column

In this example, we will sort the query result based on single column.

mysql> SELECT Name, Capital FROM Country ORDER BY Name;

The statement sorts the names of the countries in the default ascending alphabetical order.

 

 

The following query sorts the Names of the Country table in the world database in order by descending alphabetical order.

mysql> SELECT Name FROM Country ORDER BY Name DESC;

Sort multiple columns

We can also sort based on multiple columns simultaneously with different sorting orders. We can separate the columns with comma separator in the ORDER BY Clause.

The Continent column in the Country table is enum type.  Th sort order for the enum type is the list placement order.

mysql> DESC Country;

Continent | enum(‘Asia’,’Europe’,’North America’,’Africa’,’Oceania’,’Antarctica’,’South America’)

Let’s sort the query result based on multiple columns Continent in descending order and the Name in ascending order.

mysql> SELECT Name, Continent FROM Country
-> ORDER BY Continent DESC, Name;

 

MySQL Tutorials

MySQL Tutorials on this website:

https://www.testingdocs.com/mysql-tutorials-for-beginners/

For more information on MySQL Database:

https://www.mysql.com/

Exit mobile version