Sorting Rows
Now that we know how to select data from our tables and filter the results, let’s cover one last concept before we end this chapter. Let’s look at how we can sort the results returned by the SELECT statement.
To do that, we use the ORDER BY clause. We can choose to sort the results based on one or more columns.
Suppose we want to sort the rows of the employees table using gender, followed by the employee’s name (em_name), we write
SELECT * FROM employees ORDER BY gender, em_name;
This results in the records of female employees being displayed first, followed by male employees (since the letter F comes before M).
Within each gender, the records will be sorted by the employees’ names.
Note that the default sorting order is ascending. If we want to sort by descending order, we use the DESC keyword as shown below:
SELECT * FROM employees ORDER BY gender DESC, em_name;
...