MySQL

Sort Multiple Columns

It is often necessary to sort data by more than one column. For example, if you are displaying an employee list, you might want to display it sorted by last name and first name (first sort by last name, and then within each last name sort by first name). This would be useful if there are multiple employees with the same last name.

To sort by multiple columns, simply specify the column names separated by commas (just as you do when you are selecting multiple columns).

The following code retrieves three columns and sorts the results by two of them first by price and then by name.

SELECT prod_id, prod_name, prod_price
FROM products
ORDER BY prod_price, prod_name;

+---------+------------+------------+
| prod_id | prod_name  | prod_price |
+---------+------------+------------+
| 8       | product 8  |       1.80 |
| 2       | product 2  |       3.99 |
| 10      | product 10 |       4.75 |
| 1       | product 1  |       5.99 |
| 7       | product 7  |       7.00 |
| 3       | product 3  |       8.99 |
| 6       | product 6  |       8.99 |
| 5       | product 5  |       9.09 |
| 11      | product 11 |      10.25 |
| 4       | product 4  |      13.99 |
| 9       | product 9  |      20.00 |
+---------+------------+------------+

It is important to understand that when you are sorting by multiple columns, the sort sequence is exactly as specified. In other words, using the output in the previous example, the products are sorted by the prod_name column only when multiple rows have the same prod_price value. If all the values in the prod_price column had been unique, no data would have been sorted by prod_name.