MySQL ORDER BY clause

The ORDER BY clause in MySQL is used to sort the result set of a query in ascending or descending order. It is used in the SELECT statement to sort the rows returned by the query based on one or more columns.

The basic syntax of the ORDER BY clause is as follows:

SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;

n this syntax, column1, column2, ... are the columns that you want to retrieve data from, table_name is the name of the table that contains the data, and [ASC|DESC] specifies the sorting order. The default sorting order is ascending (ASC), but you can also specify descending order (DESC) if you want the results to be sorted in descending order.

Here is an example of using the ORDER BY clause to sort the rows returned by a query based on a single column:

SELECT *
FROM employees
ORDER BY last_name ASC;

In this example, the employees table contains data about employees, including first_name, last_name, and hire_date. The query retrieves all the rows from the table and sorts them in ascending order based on the last_name column.

To sort the rows based on multiple columns, you can list the columns in the ORDER BY clause separated by commas. Here is an example:

SELECT *
FROM employees
ORDER BY hire_date DESC, last_name ASC;

In this example, the rows are sorted first by hire_date in descending order, and then by last_name in ascending order. This means that employees who were hired most recently will appear at the top of the result set, and employees who have the same hire date will be sorted by their last names.

In conclusion, the ORDER BY clause in MySQL is a powerful tool for sorting the result set of a query. It allows developers to easily retrieve data in a specific order based on one or more columns, making it a valuable tool for data analysis and management.

Example for MySQL ORDER BY clause

SELECT name FROM table_name WHERE 

ORDER BY name

Output of Above Example


+——————-+
| name |
+——————-+
| Alger |
| Alkmaar |
| Almere |
| Amersfoort |
| Amsterdam |
| Annaba |
| Apeldoorn |
| Arnhem |
| ´s-Hertogenbosch |
| Batna |
+——————-+
10 rows in set (0.00 sec)