How do you sort by multiple fields?
To sort data by multiple fields, list several columns separated by commas after ORDER BY.
Syntax
sql
SELECT *
FROM table_name
ORDER BY field1 [ASC|DESC], field2 [ASC|DESC], field3 [ASC|DESC];SQL sorts in the order the fields are listed: first by the first one, then within each group by the second, and so on.
Example
sql
SELECT name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;What happens:
- First, all rows are grouped by department, alphabetically (
ASC); - Within each department, employees are sorted by salary, from largest to smallest (
DESC).
Another example
sql
SELECT city, last_name, first_name
FROM clients
ORDER BY city ASC, last_name ASC, first_name ASC;First clients are sorted by city, then within that, by last name, and if the last name matches, by first name.
Summary:
ORDER BY can contain several fields, SQL applies the sort sequentially, left to right.
Each field can be sorted in its own direction (ASC or DESC).
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.