Sub topic 9
Sorting Results with ORDER BY
This chapter assumes you can write a basic SELECT ... FROM ... WHERE query and can run it in SQL*Plus, SQL Developer, or SQL Worksheet. It also assumes you know what NULL means. The examples use the HR sample schema, with a few DUAL-based queries where a real table would add noise.
Why you need ORDER BY
A relational table has no built-in row order. Oracle returns rows in whatever order is cheapest. That order can depend on the access path, on parallel execution, on block layout, or on a new index. A query without ORDER BY may return rows in the same order for months and then change after a reorganization or an upgrade.
ORDER BY is the only clause that guarantees the order of the result. If your code, report, or screen depends on order, state it explicitly.
SELECT employee_id, first_name, last_name, salary
FROM employees
WHERE department_id = 50
ORDER BY salary DESC, last_name;ORDER BY is the last clause of the query, apart from the row limiting clause, which comes after it.
Basic syntax: ASC, DESC and multiple keys
Each sort key is an expression followed by an optional direction.
ASCis the default. It sorts from smallest to largest, from earliest to latest, and from A to Z.DESCreverses the order.- Keys are separated by commas. Oracle sorts by the first key, then uses the second key only to order rows that tie on the first, and so on.
- Direction applies to one key only. In
ORDER BY salary DESC, last_name, onlysalaryis descending.
A common mistake is writing ORDER BY last_name, first_name DESC and expecting both keys to be descending. Write DESC after each key that needs it.
What you can sort by
The sort key does not have to be a plain column. Oracle accepts several forms.
| Form | Example | Notes |
|---|---|---|
| Column name | `ORDER BY last_name` | The column need not appear in the select list (see the DISTINCT restriction below). |
| Column alias | `ORDER BY annual_pay` | Allowed because `ORDER BY` is processed after `SELECT`. |
| Expression | `ORDER BY salary * 12` | Any expression over columns of the query. |
| Position | `ORDER BY 3` | The third item in the select list. Counting starts at 1. |
SELECT last_name, salary * 12 AS annual_pay
FROM employees
WHERE department_id = 80
ORDER BY annual_pay DESC, last_name;The alias annual_pay works in ORDER BY but not in WHERE. The next diagram shows why.
WHERE runs before SELECT, so aliases do not exist yet when it runs. ORDER BY runs after SELECT, so it can see them. This is the logical order only. The optimizer may physically do the work differently as long as the result is the same.
Sorting by position
ORDER BY 2, 3 DESC is shorthand for sorting by the second and third select-list items. It is handy in an ad hoc query. In saved code it is fragile, because adding or reordering a column in the select list silently changes the sort. Prefer names or aliases in anything that will be maintained.
Sorting by a column you do not select
In a plain query you can sort by a column you do not display.
SELECT first_name, last_name
FROM employees
ORDER BY hire_date;Adding DISTINCT changes this. Oracle must decide which rows are duplicates using only the selected values, so a sort key outside the select list is ambiguous. The query fails with ORA-01791: not a SELECTed expression.
-- Fails with ORA-01791
SELECT DISTINCT department_id
FROM employees
ORDER BY hire_date;The fix is either to add the column to the select list or to drop DISTINCT and rethink the question.
NULL ordering
Oracle treats NULL as larger than any non-NULL value when sorting. That gives these defaults:
| Direction | Where NULLs appear |
|---|---|
| `ASC` | Last |
| `DESC` | First |
The second row of the table surprises people. A "top earners by commission" query sorted DESC puts all the employees with no commission at the top.
SELECT last_name, commission_pct
FROM employees
ORDER BY commission_pct DESC;Use NULLS FIRST or NULLS LAST after a key to override the default.
SELECT last_name, commission_pct
FROM employees
ORDER BY commission_pct DESC NULLS LAST, last_name;The clause applies to one key at a time, like DESC. You can also sort on NVL(commission_pct, 0), but then NULL and 0 are tied, and an index on commission_pct can no longer be used for the sort. NULLS LAST says what you mean, so prefer it.
Sorting character data
For VARCHAR2 columns, the order depends on two session settings, NLS_SORT and NLS_COMP. With the defaults, the sort is binary. Oracle compares the character codes, so in ASCII-based character sets every uppercase letter sorts before every lowercase letter.
WITH t (letter) AS (
SELECT 'b' FROM dual UNION ALL
SELECT 'B' FROM dual UNION ALL
SELECT 'a' FROM dual UNION ALL
SELECT 'A' FROM dual
)
SELECT letter
FROM t
ORDER BY letter;The result is A, B, a, b. For a case-insensitive order, sort by an expression and add the raw value as a tie-breaker so the output is still deterministic.
WITH t (letter) AS (
SELECT 'b' FROM dual UNION ALL
SELECT 'B' FROM dual UNION ALL
SELECT 'a' FROM dual UNION ALL
SELECT 'A' FROM dual
)
SELECT letter
FROM t
ORDER BY UPPER(letter), letter;This returns A, a, B, b. Another approach is ALTER SESSION SET NLS_SORT = BINARY_CI, which makes sorting case-insensitive. Comparisons in WHERE follow it only when NLS_COMP = LINGUISTIC is also set. Language-specific rules, such as accented letters, come from other NLS_SORT values like FRENCH.
Numbers stored as text
A string column sorts character by character, not by numeric value, so '10' sorts before '9'.
WITH t (v) AS (
SELECT '9' FROM dual UNION ALL
SELECT '10' FROM dual UNION ALL
SELECT '2' FROM dual
)
SELECT v
FROM t
ORDER BY v;The result is 10, 2, 9. Sorting by TO_NUMBER(v) gives 2, 9, 10. The better fix is to store numbers in a NUMBER column. Dates sort chronologically when they are stored in a DATE or TIMESTAMP column. If they are text, only an ISO layout such as YYYY-MM-DD sorts correctly.
Ties and deterministic output
ORDER BY salary DESC leaves employees with equal salaries in an unspecified order. Oracle's sort is not stable, which means it does not preserve the earlier order of tied rows. Two consequences follow.
- The same query can return tied rows in different orders on different runs.
- Paging through results (page 1, page 2, and so on) can show a row twice or skip a row, because the tied rows shift between pages.
Add a final key that is unique, usually the primary key.
SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary DESC, employee_id;ORDER BY with other clauses
Three interactions come up often.
- Row limiting.
FETCH FIRST n ROWS ONLYis applied after the sort, so it returns the firstnrows of the sorted result. WithoutORDER BY, you get an arbitrarynrows.FETCH FIRST n ROWS WITH TIESalso keeps any further rows that tie with the last row on the sort keys, so it requires anORDER BY. The next chapters cover the clause in detail. - ROWNUM.
WHERE ROWNUM <= 5 ORDER BY salary DESCdoes not return the five highest salaries.ROWNUMis assigned as rows are fetched, before the sort. Sort in an inline view first, or useFETCH FIRST. - Set operators. In a
UNION,INTERSECT, orMINUSquery, a singleORDER BYgoes at the very end. It can use only column names or aliases from the first query, or positions. It cannot use arbitrary expressions. To sort by an expression, wrap the compound query in an inline view or aWITHclause, as theUPPER(letter)example above does.
Performance notes
Sorting costs CPU and memory. For large result sets Oracle may spill to temporary space on disk. Three points help in practice.
- An index on the sort column can let Oracle return rows already in order and avoid the sort. This works best when the query also has a row limit, such as
FETCH FIRST 10 ROWS ONLY. - Sorting by an expression such as
UPPER(last_name)cannot use a plain index onlast_name. A function-based index can. - Do not sort inside a query whose result is aggregated or otherwise reordered later. The extra sort is wasted work.
Quick reference
SELECT employee_id, last_name, department_id, commission_pct
FROM employees
ORDER BY department_id NULLS LAST,
commission_pct DESC NULLS LAST,
last_name,
employee_id;This sorts by department, putting employees with no department last. Within each department, it sorts by commission with NULLs last, then by last name, then by the unique employee_id so the order is always the same.
Exercise
A query returns commissionpct values with ORDER BY commissionpct DESC, and the first rows displayed are all NULL. Why does this happen, and how do you make the largest non-NULL values appear first?
Show answer
Oracle treats NULL as larger than any value, so in a descending sort NULLs come first. Add NULLS LAST after the key: ORDER BY commission_pct DESC NULLS LAST.
Exercise
This query raises ORA-01791. Explain why, and give one way to fix it. SELECT DISTINCT departmentid FROM employees ORDER BY hiredate;
Show answer
DISTINCT removes duplicates using only the selected columns, so a sort key that is not in the select list is ambiguous. Either add hiredate to the select list (which changes what DISTINCT considers a duplicate) or sort by departmentid, which is selected: ORDER BY department_id.
Exercise
Write a query on employees that lists last_name and salary, highest salary first. Employees with the same salary must appear in the same order every time the query runs. Return only the top 10 rows.
Show answer
SELECT lastname, salary FROM employees ORDER BY salary DESC, employeeid FETCH FIRST 10 ROWS ONLY; The unique employee_id key makes ties deterministic, and FETCH FIRST is applied after the sort.