MySQL ORDER BY



Summary: In this chapter, we will learn how to sort a result set using MySQL ORDER BY clause.

The MySQL ORDER BY Keyword

Introduction to MySQL ORDER BY clause

When we use the SELECT statement to query data from a table, the result set is not sorted in any orders. The ORDER BY keyword is used to sort the result-set by one or more columns.

MySQL ORDER BY Syntax:

MySQL ORDER BY examples

We will continue with the employees table data in the sample database as shown in the picture below.

selectall_query

The following query selects employees data from the employees table and sorts it based on last name in ascending order.

MySQL-ORDERBY-Asc

In above Query we can see ORDER BY keyword sorts the records in ascending order by default. If we want to sort the contacts by last name in descending order, we need to specify the DESC in the ORDER BY clause as the following query:

MySQL-ORDERBY-Desc

We can sort multiple columns also using ORDER BY clause with ASC and DESC order. for example we want to sort the employees data by last name in descending order and first name in ascending order, we need to specify both  DESC and ASC in the corresponding column as follows:

MySQL-ORDERBY-MULTIPLECOLUMN

In the query above, the ORDER BY  clause sorts the result set by the first name in ascending order first and then sorts the sorted result set by the last name in descending order to produce the final result set.

In this chapter, we’ve learnt how to sort a result set by using the MySQL ORDER BY clause.



Design a site like this with WordPress.com
Get started