Order By Multiple Cols in SQL
ORDER BY Multiple Columns in SQL
You can sort query results by more than one column using ORDER BY. This lets you define a priority of sorting.
? Syntax:
SELECT column1, column2, ...FROM table_nameORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;The results are sorted first by
column1.If there are ties in
column1, then sorting proceeds bycolumn2.And so on for more columns.
? Example:
Sort employees by department_id ascending, then by salary descending within each department:
SELECT employee_name, department_id, salaryFROM employeesORDER BY department_id ASC, salary DESC;How this works:
Rows are grouped by
department_idin ascending order.Within each department group, rows are sorted by
salaryin descending order.
Notes:
You can mix ascending and descending order on different columns.
Ordering can be on any columns, including expressions or aliases.
Want an example with ORDER BY multiple columns plus LIMIT?