The ORDER BY Clause

So far, you have seen that data is fetched from the database in no particular order. To specify the sorting on the result of a query, you can add an ORDER BY clause.

Sorting on a Single Column

The following example retrieves all the products in order of price. The keywords ORDER BY are followed by the name of the column on which you want to sort.

mysql> SELECT *
    -> FROM products
    -> ORDER BY price;
+------+----------------+--------+-------+
| code | name           | weight | price |
+------+----------------+--------+-------+
| MINI | Small product  |   1.50 |  5.99 |
| MIDI | Medium product |   4.50 |  9.99 |
| MAXI | Large product  |   8.00 | 15.99 |
+------+----------------+--------+-------+
3 rows in set (0.00 sec)

Sort Columns

The sort ...

Get Sams Teach Yourself MySQL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.