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:
1
2
3
4
5
6
| SELECT column_name, column_name FROM table_name ORDER BY column_name ASC | DESC , column_name ASC | DESC ; |
The ASC keyword for ascending and the DESC keyword for descending. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, we can use the DESC keyword.
MySQL ORDER BY examples
We will continue with the employees table data in the sample database as shown in the picture below.
The following query selects employees data from the employees table and sorts it based on last name in ascending order.
1
2
3
4
5
6
| SELECT employeeid, firstName, lastName, jobtitle FROM employees ORDER BY lastName; |
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:
1
2
3
4
5
6
| SELECT employeeid, firstName, lastName, jobtitle FROM employees ORDER BY lastName 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:
1
2
3
4
5
6
7
| SELECT employeeid, firstName, lastName, jobtitle FROM employees ORDER BY firstname ASC , lastName DESC ; |
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.
MySQL LIKE MySQL UNION
MySQL LIKE MySQL UNION