Sorting results
You can order the result based on the column or aliased column. You can be specify DESC
for descending order or ASC
for ascending. By default, ordering will be ascending. You can combine the  LIMIT
clause with ORDER BY
to limit the results.
How to do it...
Find the employee IDs of the first five top-paid employees.
mysql> SELECT emp_no,salary FROM salaries ORDER BY salary DESC LIMIT 5;
+--------+--------+
| emp_no | salary |
+--------+--------+
| 43624 | 158220 |
| 43624 | 157821 |
| 254466 | 156286 |
| 47978 | 155709 |
| 253939 | 155513 |
+--------+--------+
5 rows in set (0.74 sec)
Instead of specifying the column name, you can also mention the position of the column in the SELECT
statement. For example, you are selecting the salary at the second position in the SELECT
statement. So, you can specify ORDER BY 2
:
mysql> SELECT emp_no,salary FROM salaries ORDER BY 2 DESC LIMIT 5; +--------+--------+ | emp_no | salary | +--------+--------+ | 43624 | 158220 | | 43624 ...