To sort data based on multiple columns in MySQL, you use the ORDER BY clause, specifying the columns you want to sort by, along with their sort order (ASC for ascending or DESC for descending). MySQL will prioritize sorting based on the first column and then sort rows with the same values in that column based on subsequent columns.
Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
Example:
Consider a table employees with the following columns: id, name, department, and salary.
To sort employees by department in ascending order and by salary in descending order:
SELECT id, name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;
Explanation:
1. Rows are first sorted by department in ascending order.
2. If multiple employees belong to the same department, they are sorted by salary in descending order within that department.
Notes:
You can include as many columns as needed in the ORDER BY clause.
The default sort order is ascending (ASC) if not explicitly specified.
No comments:
Post a Comment