How to Use ROW_NUMBER in Oracle

Last updated August 25, 2026 · By the SaturnSQL team

ROW_NUMBER() OVER (ORDER BY ...) assigns a unique rank to each row. Add PARTITION BY to restart numbering per group, the standard top-N-per-group pattern.

SELECT employee_id, department_id, salary,
       ROW_NUMBER() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees;

Top N per group

PARTITION BY resets the count for each department, so ROW_NUMBER 1 is the highest earner in every department, not just overall. Since ROW_NUMBER is a window function it cannot appear directly in WHERE, so filter it from an inline view or a WITH clause.

SELECT * FROM (
  SELECT employee_id, department_id, salary,
         ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rn
  FROM employees
) WHERE rn <= 3;

ROW_NUMBER always produces a strict 1, 2, 3, ... sequence even when values tie; two employees with the identical salary get different numbers depending on tiebreak order. Use RANK or DENSE_RANK if ties should share a position.

Run this in SaturnSQL

SaturnSQL is a browser-based SQL editor for teams: shared query library, schema-aware autocomplete, and scheduled exports to Google Sheets and Slack.

Try it free

Do more with Oracle

Related Oracle guides