Sub topic 11
Sorting results with ORDER BY
This chapter assumes you can write a basic SELECT ... FROM ... WHERE query and know what tables, rows, and columns are. The examples use an employees table with the columns employee_id, first_name, last_name, department, salary, hire_date, and manager_id. They run on PostgreSQL, MySQL, and SQLite unless noted.
Why you need ORDER BY
A relational table is an unordered set of rows. When you run a query without ORDER BY, the database returns rows in whatever order is cheapest for its execution plan. That order often looks stable. It might match insertion order or primary key order. It can still change after an UPDATE, a new index, a vacuum, a parallel scan, or a version upgrade.
SELECT first_name, last_name, salary
FROM employees;The query above guarantees which rows come back, but not their order. If your application, report, or test depends on order, you must say so.
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary;ORDER BY is the only clause that guarantees the order of the result. It is written last, after FROM and WHERE.
Basic syntax: ASC and DESC
After ORDER BY you list a sort key, which is a column or expression. You can add a direction.
ASCmeans ascending: smallest to largest, A to Z, oldest to newest. It is the default, soORDER BY salaryandORDER BY salary ASCare identical.DESCmeans descending: largest to smallest, Z to A, newest to oldest.
SELECT first_name, last_name, hire_date
FROM employees
ORDER BY hire_date DESC;This lists the most recently hired employees first. Writing ASC explicitly is optional, but many teams do it to make the intent obvious.
The direction applies only to the key right before it. This matters once you sort by several keys. The next chapter covers that case.
Sorting works together with WHERE
WHERE removes rows first, and ORDER BY then sorts the survivors.
SELECT first_name, last_name, salary
FROM employees
WHERE department = 'Sales'
ORDER BY salary DESC;Sorting is part of the query's cost. On a large result, the database may need to sort millions of rows, which uses memory or temporary disk space. An index on the sort column can let the database read rows already in order and skip the sort. Filtering with WHERE first keeps the sorted set small.
What you can sort by
The sort key does not have to be a plain column from the select list. It can be any of the following.
A column you do not display
You can sort by a column that you do not return.
SELECT first_name, last_name
FROM employees
ORDER BY hire_date;The output shows only names, but the rows are ordered by hire date. This works because sorting is evaluated on the underlying rows before the final columns are trimmed. One exception is SELECT DISTINCT, covered under common errors below.
An expression
SELECT first_name, last_name
FROM employees
ORDER BY LENGTH(last_name) DESC;Here LENGTH works in PostgreSQL, MySQL, and SQLite. SQL Server uses LEN. Any expression that produces a comparable value is allowed.
A column alias
SELECT first_name, salary * 12 AS annual_salary
FROM employees
ORDER BY annual_salary DESC;Aliases work in ORDER BY because the database evaluates SELECT before it sorts. The same alias would fail in WHERE, which runs earlier. A later chapter explains the full evaluation order.
Some databases accept an alias only when it stands alone. PostgreSQL, for example, rejects ORDER BY annual_salary + 1, because the alias is part of a larger expression. If you need that, repeat the original expression: ORDER BY salary * 12 + 1.
A column position
You can refer to a select-list item by its position, starting at 1.
SELECT first_name, last_name, salary
FROM employees
ORDER BY 3 DESC;This sorts by salary, the third item. It is handy for quick exploration. Avoid it in saved queries. If someone reorders or adds select-list columns, the sort silently changes, and nothing fails.
How the pieces fit together
The diagram shows the logical order in which a simple query is processed. This is a conceptual order. The optimizer may physically do things differently, but the results must match it.
Because ORDER BY runs last, it can see aliases and, in most cases, the original columns too.
How different data types sort
The sort order depends on the data type of the key. This causes many surprises.
| Data type | Ascending order | Watch out for |
|---|---|---|
| Numbers | Numeric: 2, 10, 100 | None in normal use |
| Dates and timestamps | Chronological | Dates stored as text in a non-ISO format such as `'12/01/2021'` sort as text |
| Text | By the database's collation rules | Case, accents, and locale vary between systems |
| Booleans | `false` before `true` in PostgreSQL | Support and representation vary by database |
Numbers stored as text
If a column holds numbers in a text type, the sort is alphabetical, character by character. The values '9', '10', and '100' sort as '10', '100', '9'. The fix is to store numbers in a numeric type. If you cannot change the schema, cast in the query:
SELECT employee_id
FROM employees
ORDER BY CAST(employee_id AS INTEGER);This example is only meaningful if employee_id is stored as text. If it is already numeric, the cast changes nothing.
Text and collation
A collation is the set of rules that decides how characters compare. It determines whether 'apple' equals 'Apple', whether 'Z' comes before 'a', and where accented letters land.
- Binary or C-style collations compare character codes, so every uppercase letter sorts before every lowercase letter:
Zoecomes beforeadam. - Locale-aware collations, the default in many PostgreSQL and MySQL setups, treat
adamandZoein dictionary order. - SQLite's default
BINARYcollation is case-sensitive. MySQL's common default collations are case-insensitive.
To get the same case-insensitive result everywhere, sort on a normalized expression:
SELECT last_name, first_name
FROM employees
ORDER BY LOWER(last_name);A function on the sort key can prevent the database from using a plain index to avoid sorting. Some systems let you create an index on LOWER(last_name) to fix that.
Ties and unstable order
When two rows have the same sort key, SQL does not say which comes first. If three employees earn 50000, ORDER BY salary may return them in one order today and another tomorrow. This matters most when you page through results or compare outputs in automated tests. The remedy is to add a second key that makes the order unique, such as employee_id. The next chapter shows how to combine several keys.
Common errors
- Placing ORDER BY before WHERE. The clause order is fixed:
SELECT,FROM,WHERE,ORDER BY. Swapping them is a syntax error. - Using an alias in WHERE.
WHERE annual_salary > 40000fails, becauseWHEREruns before the alias exists. Repeat the expression:WHERE salary * 12 > 40000. - Sorting a DISTINCT query by a hidden column.
SELECT DISTINCT department FROM employees ORDER BY hire_dateis ambiguous. Each department maps to many hire dates, so there is no single value to sort by. PostgreSQL raises an error saying theORDER BYexpressions must appear in the select list. Sort by a column you return. - Relying on position numbers.
ORDER BY 2breaks silently when the select list changes. An out-of-range number such asORDER BY 9on a three-column query gives an error. - Assuming order without ORDER BY. A query that "always" returns sorted rows in development can return a different order in production.
- Forgetting that DESC applies to one key. In
ORDER BY a, b DESC, onlybis descending.
Putting it together
This query filters, computes, names a value, and sorts by that name:
SELECT first_name, last_name, salary * 12 AS annual_salary
FROM employees
WHERE department = 'Support'
ORDER BY annual_salary DESC;You can read it in evaluation order. Take employees, keep the Support rows, compute each annual salary, then sort from highest to lowest.
Exercise
A query reads SELECT first_name, salary * 12 AS annual_salary FROM employees WHERE annual_salary > 60000 ORDER BY annual_salary;. It fails. Explain why and give a corrected version that still sorts by the alias.
Show answer
WHERE is evaluated before SELECT, so the alias annual_salary does not exist yet when the filter runs. ORDER BY runs after SELECT, so the alias works there. Repeat the expression in the filter: SELECT first_name, salary * 12 AS annual_salary FROM employees WHERE salary * 12 > 60000 ORDER BY annual_salary;. Writing WHERE salary > 5000 is equivalent for positive salaries and is simpler.
Exercise
A product_code column of type text holds the values '7', '20', and '100'. What order does ORDER BY product_code return, and how can you get numeric order without changing the table?
Show answer
The sort is character by character, so the result is '100', '20', '7'. Cast the key to a numeric type in the sort: ORDER BY CAST(product_code AS INTEGER). Storing the values in a numeric column is the better long-term fix.
Exercise
Why can two runs of SELECT first_name, salary FROM employees ORDER BY salary; return different row orders even though both are sorted correctly?
Show answer
Several employees can share the same salary. SQL does not define the order of rows that tie on the sort key, so the database may return them in any order. Adding a unique second key, such as employee_id, makes the order repeatable.