Information Technology · Ch 3 — Relational Database Management System - II
Sorting the Result — ORDER BY
Sorting the Result — ORDER BY
By default, a SELECT query returns rows in no particular guaranteed order. To present the result sorted, we add an ORDER BY clause, which always comes last in the query. ORDER BY sorts the output by one or more columns, either ascending (smallest first, the default, keyword ASC) or descending (largest first, keyword DESC).
To list employees from the highest salary to the lowest:
SELECT Name, Salary FROM Employee
ORDER BY Salary DESC;
To list them by name in alphabetical (ascending) order — where ASC may be left out because it is the default:
SELECT Name FROM Employee
ORDER BY Name;
Sorting by more than one column. We can give several columns separated by commas; MySQL sorts by the first column, and uses the next column only to break ties. For example, to list employees grouped by department (alphabetically) and, within each department, from highest salary to lowest:
SELECT Dept, Name, Salary FROM Employee
ORDER BY Dept ASC, Salary DESC;
ORDER BY combines naturally with a WHERE clause, which is written before it. For example, the IT-department employees sorted by joining date (earliest first):
SELECT Name, JoinDate FROM Employee
WHERE Dept = 'IT'
ORDER BY JoinDate ASC;
``` …
A SELECT clause, written last, that sorts the result by one or more columns — ascending (ASC, the default) o …
Listing several columns in ORDER BY (separated by commas) sorts by the first column and uses each later column only to break ties among equal v …