Sub topic 4
Ordering Rows Inside a Partition
This chapter assumes you know SELECT, WHERE, ORDER BY, GROUP BY, and inline views. An analytic function calculates a value for each input row. The ORDER BY inside its OVER clause defines the sequence that the function uses.
The window `ORDER BY`
An analytic clause commonly has this form:
function_name(value) OVER (
PARTITION BY grouping_columns
ORDER BY ordering_columns
)PARTITION BY divides rows into independent groups. ORDER BY arranges rows within each group. The function then processes each row in that order.
For example, this query numbers employees from the highest salary to the lowest salary within each department:
SELECT employee_id,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS salary_position
FROM employees;The analytic ORDER BY does not sort the final result set. It only controls how ROW_NUMBER assigns values. To display the result in the same order, add a separate query-level ORDER BY:
SELECT employee_id,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS salary_position
FROM employees
ORDER BY department_id, salary DESC;These are two different operations:
| Clause | Purpose |
|---|---|
| `ORDER BY` inside `OVER` | Controls analytic calculation |
| Final `ORDER BY` | Controls displayed row order |
Sorting direction and multiple columns
Use ASC for ascending order and DESC for descending order. Ascending is the default.
You can provide several ordering columns. Oracle compares the second column only when rows tie on the first column:
SELECT employee_id,
department_id,
salary,
hire_date,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, hire_date ASC, employee_id
) AS rn
FROM employees;This gives higher salaries priority. Among equal salaries, earlier hires come first. If those values also match, employee_id supplies a final tiebreaker.
Ties and deterministic results
If the window ordering does not uniquely identify a row, Oracle may choose any order among tied rows. The result can change between executions, especially when the query plan or physical storage changes.
Null values also affect ordering. State the desired behavior explicitly with NULLS FIRST or NULLS LAST:
SELECT employee_id,
salary,
ROW_NUMBER() OVER (
ORDER BY salary DESC NULLS LAST, employee_id
) AS rn
FROM employees;For descending order, Oracle normally places nulls first unless you specify otherwise. Explicit null handling makes the query's intent clear.
Exercise
Why can two employees with the same salary receive different row numbers, and how can you make their numbering repeatable?
Show answer
The window ORDER BY does not uniquely order tied rows. Add a stable column, such as employee_id, after salary in the window ORDER BY.