Sub topic 12
Sorting by several columns, ascending and descending
This chapter assumes you can write a basic SELECT ... FROM ... WHERE query and have seen a single-column ORDER BY. You should also know what a NULL is. The examples use the employees table from earlier chapters, with columns such as first_name, last_name, department, salary, hire_date, and manager_id.
Why one sort column is often not enough
Sorting by one column leaves ties. If you sort employees by department, every Sales employee has the same sort key. The database is then free to return those rows in any order. That order can change between runs, between database versions, or after an index is added.
A second sort column breaks those ties. A third breaks the ties that remain, and so on. This is what makes a result reproducible and readable.
The syntax
List the sort keys after ORDER BY, separated by commas. Each key can carry its own direction, ASC (ascending, the default) or DESC (descending).
SELECT first_name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;The database reads the keys from left to right:
- It sorts all rows by
department, alphabetically. - Within each group of rows that share a department, it sorts by
salary, highest first.
The result lists the departments in alphabetical order, and the best-paid person comes first inside each one.
The second key is consulted only when the first is equal. A later key never overrides an earlier one.
Direction applies to one key at a time
The most common mistake is to assume that a direction keyword covers the whole list. It does not. Each key has its own direction, and a key with no keyword is ascending.
SELECT first_name, department, salary
FROM employees
ORDER BY department, salary DESC;This sorts department ascending and salary descending. It is the same as the first query. To sort both descending, write the keyword twice:
SELECT first_name, department, salary
FROM employees
ORDER BY department DESC, salary DESC;Writing ORDER BY department, salary DESC and expecting both columns to be descending is a bug that returns plausible-looking output. Check the direction of every key.
| Clause | Department order | Salary order within a department |
|---|---|---|
| `ORDER BY department, salary` | A to Z | lowest first |
| `ORDER BY department, salary DESC` | A to Z | highest first |
| `ORDER BY department DESC, salary` | Z to A | lowest first |
| `ORDER BY department DESC, salary DESC` | Z to A | highest first |
A worked example
Suppose employees contains these rows.
| first_name | department | salary |
|---|---|---|
| Ana | Sales | 52000 |
| Ben | Support | 41000 |
| Cara | Sales | 61000 |
| Dev | Marketing | 55000 |
| Eli | Sales | 52000 |
| Fay | Marketing | 48000 |
Running ORDER BY department ASC, salary DESC gives:
| first_name | department | salary |
|---|---|---|
| Dev | Marketing | 55000 |
| Fay | Marketing | 48000 |
| Cara | Sales | 61000 |
| Ana | Sales | 52000 |
| Eli | Sales | 52000 |
| Ben | Support | 41000 |
Marketing comes before Sales, and Sales before Support. Inside Sales, Cara has the highest salary and comes first. Ana and Eli have the same department and the same salary, so no key separates them. Either of them may appear first.
Making the result deterministic
When two rows tie on every listed key, the database may return them in any order. This matters most when you combine sorting with a row limit or when you paginate, because rows can then move across page boundaries or appear twice.
Add a final key that is unique, usually the primary key. Assuming employees has an employee_id column:
SELECT first_name, department, salary
FROM employees
ORDER BY department ASC, salary DESC, employee_id ASC;Now Ana and Eli always appear in the same order, because their employee_id values differ.
Sorting by expressions, positions, and aliases
A sort key does not have to be a plain column. It can be any expression.
SELECT first_name, last_name, salary * 12 AS annual_salary
FROM employees
WHERE salary > 40000
ORDER BY annual_salary DESC, last_name ASC;The alias annual_salary works in ORDER BY because sorting happens after SELECT has produced the output columns. You can also repeat the expression (ORDER BY salary * 12 DESC), which works everywhere, including in the WHERE clause where aliases do not.
Most databases also accept a column position, counting from 1 in the select list:
SELECT first_name, department, salary
FROM employees
ORDER BY 2, 3 DESC;This sorts by department (position 2) and then by salary (position 3) descending. Positions are short, but they break silently if someone reorders the select list. Prefer names in code that will be maintained.
You can also sort by a column you did not select, in most cases:
SELECT first_name, last_name
FROM employees
ORDER BY hire_date DESC, last_name;The exception is a query with SELECT DISTINCT. There, the sort key must appear in the select list, because the database must decide which of several hidden values to sort by after collapsing duplicates. PostgreSQL reports an error in this case, and other databases behave similarly or inconsistently.
Mixing text and numbers: collation and types
How a column sorts depends on its data type.
- Numbers sort by value, so 9 comes before 10.
- Dates sort chronologically when stored as
DATEorTIMESTAMP. - Text sorts by the database's collation, a set of rules for comparing characters. A collation may be case-sensitive or not, and may treat accented letters in a particular way. Some collations place
'apple'after'Zebra', while others place it before. - Numbers stored as text sort character by character, so
'10'comes before'9'.
If a multi-column sort puts rows in an unexpected order, check the column types and the collation before you suspect the query. A text column holding numbers is a frequent cause.
NULL values in multi-column sorts
NULL is not a value, so databases need a rule for where it goes. The rule differs by product. PostgreSQL and Oracle treat NULL as larger than any value, so it comes last in ascending order and first in descending order. MySQL and SQLite treat NULL as smaller, so it comes first in ascending order. SQL Server also puts it first in ascending order.
Each key follows the rule independently. In the following query, employees with no manager appear at the top or bottom of the list depending on the database, and then ties are broken by salary:
SELECT first_name, manager_id, salary
FROM employees
ORDER BY manager_id ASC, salary DESC;PostgreSQL, Oracle, SQLite, and recent versions of other databases let you state the placement directly:
SELECT first_name, manager_id, salary
FROM employees
ORDER BY manager_id ASC NULLS LAST, salary DESC;MySQL and SQL Server do not support NULLS FIRST or NULLS LAST. A portable workaround sorts first on whether the value is NULL:
SELECT first_name, manager_id, salary
FROM employees
ORDER BY CASE WHEN manager_id IS NULL THEN 1 ELSE 0 END,
manager_id ASC,
salary DESC;The CASE expression yields 0 for rows with a manager and 1 for rows without one, so the NULL rows come last in every database. The next chapter covers NULL ordering in more detail.
Combining a multi-column sort with a limit
A sort with a limit gives you top-N results per the rules in the sort. With ties at the cutoff, the extra key decides who is included.
SELECT first_name, department, salary
FROM employees
ORDER BY salary DESC, employee_id ASC
LIMIT 5;Without employee_id, if the fifth and sixth employees earn the same, the database could return either one, and it could return a different one on the next run. LIMIT works in PostgreSQL, MySQL, and SQLite. The standard form, FETCH FIRST 5 ROWS ONLY, is used by other databases such as Oracle and recent SQL Server versions. SQL Server also accepts OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY after ORDER BY.
Common errors
- Assuming one
DESCcovers every key. Each key needs its own keyword. - Putting the keys in the wrong order.
ORDER BY salary DESC, departmentsorts mainly by salary, so departments are scattered. The first key is the main grouping. - Using an alias in
WHERE. Aliases are available inORDER BYbut not inWHERE, sinceWHEREruns beforeSELECT. - Relying on the output order without
ORDER BY. A table has no inherent order, even if rows seem to come back in insertion order. - Forgetting a tiebreaker. The output looks right in testing and changes later.
- Using positions after changing the select list.
ORDER BY 2points to a different column once the list changes. - Sorting numbers stored as text. The result is alphabetical, not numeric.
Exercise
Write a query on employees that lists first_name, department, and hire_date. Show departments from Z to A. Within each department, show the most recently hired person first. Make the order fully deterministic, assuming a unique employee_id column exists.
Show answer
SELECT firstname, department, hiredate
FROM employees
ORDER BY department DESC, hiredate DESC, employeeid ASC;
Each key carries its own direction. The final employee_id key separates any employees who share a department and a hire date.
Exercise
A query uses ORDER BY department, salary DESC. A colleague says both columns are sorted from high to low. Is that correct? What would you change to make it true?
Show answer
No. DESC applies only to salary, so department is sorted A to Z. To sort both from high to low, write ORDER BY department DESC, salary DESC.
Exercise
You need employees sorted by manager_id ascending with the employees who have no manager at the end, on a MySQL database. How do you do it?
Show answer
MySQL has no NULLS LAST, so sort on a NULL test first: ORDER BY CASE WHEN manager_id IS NULL THEN 1 ELSE 0 END, manager_id ASC. Rows with a manager get 0 and come first, and rows without one get 1 and come last.