MySQL ORDER BY

The ORDER BY clause in MySQL is a powerful SQL statement that allows you to sort the result set of a query based on one or more columns. This clause is particularly useful when you want to present your query results in a specific order, whether it be ascending or descending.

Syntax

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], ...;

Here’s a breakdown of the syntax:

SELECT: Specifies the columns that you want to retrieve from the table.
FROM: Specifies the table from which to retrieve the data.
ORDER BY: Indicates the sorting of the result set.
column1, column2, …: Specifies one or more columns by which to sort the result set.
[ASC|DESC]: Specifies the sort order. ASC stands for ascending (default), and DESC stands for descending.

Example

Here’s an example to illustrate how to use the ORDER BY clause:

Suppose you have a table named employees with columns employee_id, first_name, last_name, and salary. You want to retrieve the employee information sorted by salary in descending order. The SQL query would look like this:

SELECT employee_id, first_name, last_name, salary
FROM employees
ORDER BY salary DESC;

In this example, the ORDER BY clause is used to sort the result set based on the salary column in descending order. As a result, the query will return a list of employees sorted from the highest to the lowest salary.

You can also sort by multiple columns. For instance, if you want to sort by last_name in ascending order and then by salary in descending order for employees with the same last name, you can use the following query:

SELECT employee_id, first_name, last_name, salary
FROM employees
ORDER BY last_name ASC, salary DESC;

This query first sorts the result set alphabetically by the last_name column in ascending order and then sorts by the salary column in descending order for employees with the same last name.

In summary, the ORDER BY clause in MySQL is a versatile tool that allows you to control the presentation of your query results by specifying the columns and the order in which they should be sorted.