Sub topic 4
Ordering rows inside a partition
This chapter assumes you can write GROUP BY queries and have seen the OVER clause with PARTITION BY. It covers the ORDER BY that goes inside OVER: what it controls, how it differs from the query's ORDER BY, and the details that change results.
Two different ORDER BY clauses
A query with an analytic function can contain two ORDER BY clauses. They do different jobs.
- The
ORDER BYinsideOVER (...)sets the sequence of rows within each partition. The function reads that sequence to decide which row is first, which is previous, and which is next. - The
ORDER BYat the end of the query sets the order in which rows are returned to you.
Oracle does not tie the two together. A function can number rows by salary while the final result is sorted by name.
SELECT employee_id,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS salary_position
FROM employees
ORDER BY employee_id;The output is sorted by employee_id, but salary_position still counts down from the highest salary in each department. Without a final ORDER BY, Oracle guarantees no row order at all, even if the rows appear sorted in a test.
The window ORDER BY is required for some functions
Ranking and navigation functions are meaningless without a sequence, so Oracle insists on one. ROW_NUMBER, RANK, DENSE_RANK, LAG, and LEAD all need an ORDER BY in the OVER clause. If you leave it out, Oracle raises an error (ORA-30485: missing ORDER BY expression in the window specification).
Aggregate functions used as analytic functions, such as SUM and COUNT, treat the clause as optional, but adding it changes their meaning. That case is covered later in this chapter.
Syntax of the ordering list
The list inside OVER follows the same shape as an ordinary ORDER BY:
ORDER BY expression [ASC | DESC] [NULLS FIRST | NULLS LAST] [, expression ...]You can use any expression, not only plain columns. ORDER BY salary * 12 DESC and ORDER BY TRUNC(hire_date, 'YYYY') are both valid. You cannot use a column alias defined in the same SELECT list, so repeat the expression instead.
Each column in the list has its own direction. A common pattern is to sort the main measure descending and a tiebreaker ascending:
ORDER BY salary DESC, hire_date ASC, employee_idOracle sorts by salary first. It consults hire_date only for rows with equal salary, and employee_id only for rows still tied after that. ASC is the default, so it is often left out.
How NULLs are placed
Oracle treats NULL as larger than any other value when sorting. That gives these defaults:
| Direction | Default NULL position |
|---|---|
| `ASC` | `NULLS LAST` |
| `DESC` | `NULLS FIRST` |
The second default surprises many people. If you rank employees by commission_pct DESC, everyone with no commission gets the lowest row numbers, because their NULLs sort first. State the position explicitly when NULLs are possible:
SELECT employee_id,
department_id,
commission_pct,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY commission_pct DESC NULLS LAST, employee_id
) AS rn
FROM employees
ORDER BY department_id, rn;With NULLS LAST, rows that have a commission are numbered first, from highest to lowest. Rows without one follow, ordered by employee_id.
What the ordering does to each function
The same sequence feeds different functions in different ways.
ROW_NUMBERassigns 1, 2, 3, and so on in sequence order.RANKandDENSE_RANKgive equal values the same rank, so they depend on which rows are equal under the ordering list.LAGreturns a value from the row before the current one in the sequence.LEADreturns it from the row after.
For LAG and LEAD, the direction of the ordering decides what "previous" means. Reversing the direction swaps their roles:
SELECT sales_month,
amount,
LAG(amount) OVER (ORDER BY sales_month) AS prev_in_time,
LEAD(amount) OVER (ORDER BY sales_month DESC) AS also_prev_in_time
FROM monthly_sales
ORDER BY sales_month;In the last two columns, LEAD over a descending order gives the same values as LAG over an ascending one. The default for the missing end is also the same: NULL unless you supply a default.
Ties in the ordering
When two rows have identical values in every ordering column, Oracle has no basis to put one before the other. These rows are called peers. For RANK and DENSE_RANK, peers get the same rank, which is intended. For ROW_NUMBER, LAG, and LEAD, the order of peers is arbitrary, and it can change between runs, after an index is added, or after the data is reloaded.
Consider two employees in department 50 with a salary of 3000. With ORDER BY salary DESC alone, either may receive ROW_NUMBER 4. A later query filtering on rn <= 4 might return a different person each time. The fix is to extend the ordering list until no two rows can match, usually by ending with a unique column:
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
)If employee_id is a primary key, the order is now fully determined. The next chapters return to ties when comparing RANK and ROW_NUMBER.
The ordering also changes aggregate functions
You can use SUM, AVG, COUNT, and similar functions with OVER. If you give them no ORDER BY, they compute over the whole partition and return the same value on every row. If you add one, Oracle applies a default window: all rows from the start of the partition up to the current row and its peers.
SELECT employee_id,
department_id,
hire_date,
SUM(salary) OVER (PARTITION BY department_id) AS dept_total,
SUM(salary) OVER (PARTITION BY department_id ORDER BY hire_date) AS running_total
FROM employees
ORDER BY department_id, hire_date;dept_total is constant within a department. running_total grows row by row. The default window is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, and RANGE includes peers. If two employees share a hire_date, both rows show the same running total, which includes both salaries. To get a strict row-by-row total, add a unique tiebreaker to the ordering and write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW explicitly.
Common mistakes
- Omitting the window
ORDER BYon a ranking function and getting ORA-30485. - Expecting the window
ORDER BYto sort the output. Add a finalORDER BYfor that. - Ordering a
DESCcolumn that contains NULLs and finding NULL rows ranked first. - Leaving out a unique tiebreaker, then getting different rows from
rn <= Nfilters across runs. - Using a
SELECTalias insideOVER (ORDER BY ...). Repeat the expression instead.
Exercise
A query uses ROWNUMBER() OVER (PARTITION BY departmentid ORDER BY bonus DESC) AS rn on a table where some employees have a NULL bonus. Employees with no bonus get rn = 1. Rewrite the OVER clause so that employees with a bonus are numbered first, highest bonus first, and ties are broken so the numbering is the same on every run (employee_id is unique).
Show answer
Use ROWNUMBER() OVER (PARTITION BY departmentid ORDER BY bonus DESC NULLS LAST, employeeid) AS rn. In Oracle, DESC places NULLs first by default, so NULLS LAST is needed to put employees without a bonus at the end. Adding employeeid as the final ordering column makes the order fully determined when bonuses are equal.