0
0
MySQLquery~5 mins

ORDER BY multiple columns in MySQL

Choose your learning style9 modes available
Introduction

We use ORDER BY multiple columns to sort data by more than one rule. This helps organize results clearly.

When you want to sort a list of students first by grade, then by name.
When you have sales data and want to order by region and then by sales amount.
When you want to display products sorted by category and then by price.
When you want to list employees sorted by department and then by joining date.
Syntax
MySQL
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
You can choose ASC (ascending) or DESC (descending) for each column separately.
If you don't specify ASC or DESC, ascending order is the default.
Examples
This sorts employees first by department alphabetically, then by salary from highest to lowest within each department.
MySQL
SELECT * FROM employees
ORDER BY department ASC, salary DESC;
This sorts students by grade from highest to lowest, and if grades are the same, by name alphabetically.
MySQL
SELECT name, grade FROM students
ORDER BY grade DESC, name ASC;
This sorts products by category alphabetically, then by price ascending within each category.
MySQL
SELECT product_name, category, price FROM products
ORDER BY category ASC, price ASC;
Sample Program

This example creates a table of employees, inserts some data, and then selects their name, department, and salary. The results are sorted first by department alphabetically, then by salary from highest to lowest within each department.

MySQL
CREATE TABLE employees (
  id INT,
  name VARCHAR(50),
  department VARCHAR(50),
  salary INT
);

INSERT INTO employees VALUES
(1, 'Alice', 'HR', 5000),
(2, 'Bob', 'IT', 7000),
(3, 'Charlie', 'HR', 6000),
(4, 'David', 'IT', 6500),
(5, 'Eve', 'Finance', 5500);

SELECT name, department, salary FROM employees
ORDER BY department ASC, salary DESC;
OutputSuccess
Important Notes

Ordering by multiple columns helps when one column alone is not enough to sort data clearly.

Remember that the order of columns in ORDER BY matters; the first column sorts first, then the second, and so on.

Summary

ORDER BY multiple columns lets you sort data by more than one rule.

You can mix ascending and descending order for each column.

This helps organize complex data in a clear way.