The ORDER BY clause in MySQL is used to sort the result set of a query based on one or more columns. It allows you to specify the sorting order, either in ascending (ASC) or descending (DESC) order. Here's an example of using the ORDER BY clause:
Consider a table called employees with the following structure:
Syntax:
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
department VARCHAR(50),
salary DECIMAL(10,2)
);
Suppose we want to retrieve the employees from the employees table sorted by their salary in descending order. We can use the ORDER BY clause as follows:
Syntax:
SELECT * FROM employees ORDER BY salary DESC;
In the above example, the ORDER BY clause is applied to the salary column with DESC keyword, which indicates descending order. This query will return the employees sorted by their salary from highest to lowest.
You can also sort by multiple columns by specifying additional columns in the ORDER BY clause:
Syntax:
SELECT * FROM employees ORDER BY department ASC, salary DESC;
In the above example, the query will first sort the employees by the department column in ascending order, and then within each department, it will sort them by the salary column in descending order.
By default, the ORDER BY clause sorts in ascending order (ASC). If you want to explicitly specify ascending order, you can use the ASC keyword, although it is optional.
Remember to adjust the column names and table name in the examples based on your specific scenario. The ORDER BY clause can be used in combination with other clauses like WHERE, GROUP BY, or LIMIT to further refine your query results.