Multi-Column Sorting
Multi-Column Sorting: Hierarchical Ordering & Custom Expressions
When querying large enterprise tables, sorting by a single column often produces ties: multiple employees work in the same department, or multiple products share the exact same price. Multi-Column Sorting allows you to specify a primary sort column followed by secondary and tertiary "tie-breaker" columns, each with its own independent sort direction.
1. Syntax for Multi-Column Sorting
Separate each column and its desired direction with a comma:
Real-World Example:
Sort employees by Department alphabetically, and within each department, sort by Salary descending (highest paid first):
Result Grid:
+-------------+---------------+-------------+----------+ | employee_id | full_name | department | salary | +-------------+---------------+-------------+----------+ | 104 | Vikram Rao | Engineering | 95000.00 | <-- Highest salary in Engineering | 101 | Aarav Sharma | Engineering | 80000.00 | | 108 | Neha Gupta | Engineering | 65000.00 | | 102 | Priya Patel | Marketing | 72000.00 | <-- Highest salary in Marketing | 105 | Rohan Verma | Marketing | 54000.00 | +-------------+---------------+-------------+----------+
2. Sorting by Computed Expressions
You can sort results by mathematical calculations, string manipulations, or date functions directly:
3. Custom Non-Alphabetical Sorting with FIELD()
What if you need to sort records in a specific, non-alphabetical business order? For example, sorting support tickets by priority: Critical -> High -> Medium -> Low.
Standard ASC or DESC will sort alphabetically (Critical -> High -> Low -> Medium), which is incorrect! MySQL provides the FIELD() function for custom ordering:
How FIELD() Works:
FIELD(str, str1, str2, ...)returns the 1-based index position ofstrwithin the list.'Critical'returns 1,'High'returns 2,'Medium'returns 3,'Low'returns 4.- The
ORDER BYclause sorts the rows by these returned numeric values (1, 2, 3, 4)!
4. Composite Indexes for Multi-Column Sorting
When you frequently sort by multiple columns (e.g., ORDER BY department ASC, salary DESC), MySQL can satisfy the query instantaneously with zero filesort overhead if a matching Composite Index is present:
5. Best Practices & Common Pitfalls
- Avoid Sorting by Too Many Columns: Sorting by 5 or 6 columns without composite indexes consumes substantial server sorting memory (
sort_buffer_size). Stick to 1 to 3 primary sorting criteria. - Direction Specifies per Column: Remember that specifying
DESCat the end applies only to the column immediately preceding it! WritingORDER BY col1, col2 DESCsortscol1in ASC order andcol2in DESC order.
Multiple Choice Questions
1. In the statement ORDER BY state ASC, city DESC, how are the rows ordered?
A. First by city descending, then ties broken by state ascending B. First by state ascending, then ties broken by city descending C. Both columns are sorted descending D. Both columns are sorted ascending Answer: B Explanation: Multi-column sorting processes from left to right: the primary sort is applied on state ASC, and ties within the same state are ordered by city DESC.
2. Which MySQL function allows sorting string values according to a custom non-alphabetical list (e.g., 'Gold', 'Silver', 'Bronze')?
A. CUSTOM_SORT() B. FIELD() C. LIST_ORDER() D. ENUM_INDEX() Answer: B Explanation: FIELD(column, 'Gold', 'Silver', 'Bronze') returns the index position of the value in the list, enabling custom non-alphabetical sorting.
3. In the query SELECT name, dept, salary FROM staff ORDER BY dept, salary DESC;, what is the sort direction of the dept column?
A. DESC B. ASC C. Random D. Case-sensitive Answer: B Explanation: Because no direction was explicitly attached to dept, it defaults to ASC. The DESC keyword applies only to salary.
4. Which database object can eliminate the need for an in-memory Filesort when sorting by ORDER BY category ASC, price DESC?
A. A foreign key B. A composite index matching (category ASC, price DESC) C. A database view D. A trigger Answer: B Explanation: A composite B-Tree index covering the sorted columns in their required directions allows the engine to read rows already in sorted order without filesort.
5. Can an ORDER BY clause sort records based on a mathematical expression involving multiple columns?
A. No, only raw column names are permitted B. Yes, SQL supports sorting by arbitrary mathematical or functional expressions C. Only if the expression evaluates to a negative number D. Only in MySQL Workbench Answer: B Explanation: ORDER BY can sort by arbitrary expressions (e.g., ORDER BY (unit_price * quantity) DESC).
Restricting Rows with LIMIT
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Sorting Data with ORDER BY | Restricting Rows with LIMIT |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.