Sub topic 11
Sorting Results with `ORDER BY`
Assume you know the basics of relational tables and can run SQL in PostgreSQL, MySQL, or SQLite. This chapter focuses on controlling the order of rows returned by a query. SQL does not promise a useful order unless you write an ORDER BY clause.
Sort one column
ORDER BY sorts the result after the database finds the rows. The default direction is ascending, written as ASC. Text values usually sort alphabetically, numbers from smallest to largest, and dates from oldest to newest.
SELECT first_name, department, salary
FROM employees
ORDER BY salary ASC;To show the highest salaries first, use DESC:
SELECT first_name, department, salary
FROM employees
ORDER BY salary DESC;ASC and DESC apply only to the expression immediately before them. You can sort by a column that is not included in the result, although including it often makes the output easier to understand.
Sort by several columns
A database sorts by the first expression, then uses the next expression to break ties. In this query, departments appear alphabetically. Employees in the same department appear from highest salary to lowest:
SELECT first_name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;The order of expressions matters. Reversing them would sort the whole result by salary first and use the department only when salaries are equal.
You can also use a selected column's alias in ORDER BY:
SELECT first_name, salary * 12 AS annual_salary
FROM employees
ORDER BY annual_salary DESC;This is useful when sorting by a computed value. Some databases also allow a column number, such as ORDER BY 2, but aliases are clearer and safer when the select list changes.
`NULL` values in sorted output
NULL means a missing or unknown value. Its position in sorted results depends on the database and sort direction. PostgreSQL lets you state the position explicitly:
SELECT first_name, manager_id
FROM employees
ORDER BY manager_id ASC NULLS LAST;MySQL and SQLite do not support NULLS LAST in the same way. Check your database's rules when missing values affect a report or user interface.
| Goal | Typical clause |
|---|---|
| Smallest to largest | `ORDER BY salary ASC` |
| Largest to smallest | `ORDER BY salary DESC` |
| Make missing values explicit in PostgreSQL | `ORDER BY manager_id ASC NULLS LAST` |
Sort, then limit
To retrieve a top-N result, sort first and limit second:
SELECT first_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 5;LIMIT 5 is supported by PostgreSQL, MySQL, and SQLite. Standard SQL and some other databases use this form:
SELECT first_name, salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 5 ROWS ONLY;Always include ORDER BY when selecting a top-N set. Without it, the database may return any five rows.
Exercise
Write a query that returns the three lowest-paid employees, showing their names and salaries.
Show answer
SELECT first_name, salary FROM employees ORDER BY salary ASC LIMIT 3;