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 based on specified columns.
Basic Syntax:
Example: Basic ORDER BY
SELECT column1, column2, ...
FROM table_name
ORDER BY column1;
This SQL command selects specific columns (column1
, column2
, …) from a table (table_name
) and sorts the result set by column1
in ascending order by default.
Sorting in Descending Order:
Example: ORDER BY DESC
SELECT * FROM users
ORDER BY last_name DESC;
This SQL command selects all columns from the users
table and sorts the result set by last_name
in descending order.
Sorting by Multiple Columns:
Example: ORDER BY Multiple Columns
SELECT * FROM products
ORDER BY category ASC, price DESC;
This SQL command selects all columns from the products
table and sorts the result set first by category
in ascending order, then by price
in descending order.
Conclusion
The ORDER BY clause in MySQL is essential for sorting query results based on specified columns and directions (ascending or descending), providing control over how data is presented and analyzed.