MySQL Order By

The way to order your result in MySQL is to use the ORDER BY statement. The ORDER BY keyword is used to sort the result-set by a specified column.

You can sort the results by any field in an ascending or descending order by just adding ‘ORDER BY‘ at the end of your query. You would use ORDER BY field_name ASC for an ascending sort, or ORDER BY field_name DESC for a descending sort.

The ORDER BY keyword sort the records in ascending order by default.

Syntax:

SELECT field_name FROM table_name ORDER BY field_name ASC|DESC

Example:

Consider this below employee table

Id Name Age
1 James 25
2 Sachin 26
3 Bruce 25

Now we want to select all the records from employee table above, however, we want to sort the records by their name. We use the following SELECT statement:

<?php
// sort by name as ascending order – default ascending
SELECT * FROM employee ORDER BY name;
?>

The result-set look like this

Id Name Age
1 Bruce 25
2 James 26
3 Sachin 25

Now we want to select all the records from employee table above, however, we want to sort the records by their name in descending order. We use the following SELECT statement:

<?php
// sort by name as descending order
SELECT * FROM employee ORDER BY name desc;
?>

The result-set look like this

Id Name Age
1 Sachin 25
2 James 26
3 Bruce 25
Posted in MySQL