[SQL] Mastering ROW_NUMBER() OVER(PARTITION BY ...) in Oracle SQL

 

In SQL, window functions are powerful tools for analyzing and processing data efficiently. One such function, ROW_NUMBER(), allows us to assign a unique sequential number to rows within a partition. In this blog post, we'll explore how ROW_NUMBER() works, its syntax, practical use cases, and related functions.

Understanding ROW_NUMBER()

The ROW_NUMBER() function is used to generate a unique row number for each row in a result set. When combined with the PARTITION BY clause, it resets the numbering for each partition (group of rows).

Syntax:

SELECT
    column_name,
    ROW_NUMBER() OVER(PARTITION BY partition_column ORDER BY order_column) AS row_num
FROM table_name;

Explanation:

  • ROW_NUMBER(): Generates a unique sequential number for each row.

  • OVER(): Defines the window function scope.

  • PARTITION BY partition_column: Divides the dataset into groups based on partition_column. The row number resets for each partition.

  • ORDER BY order_column: Determines the order of row numbers within each partition.

Example Use Case: Employee Salary Ranking

Sample Table: employees





Query to Assign Row Numbers Based on Salary in Each Department

SELECT
    emp_id,
    name,
    department,
    salary,
    ROW_NUMBER() OVER(PARTITION BY department ORDER BY salary DESC) AS row_num
FROM employees;

Output:



Here, the row number resets for each department, assigning unique numbers within each group.



Practical Use Cases of ROW_NUMBER()

1. Finding the Highest-Paid Employee in Each Department

SELECT * FROM (
    SELECT
        emp_id,
        name,
        department,
        salary,
        ROW_NUMBER() OVER(PARTITION BY department ORDER BY salary DESC) AS row_num
    FROM employees
) ranked
WHERE row_num = 1;

Output:



2. Implementing Pagination

For large datasets, pagination is essential. ROW_NUMBER() can help create paginated results:

SELECT * FROM (
    SELECT
        emp_id,
        name,
        department,
        salary,
        ROW_NUMBER() OVER(ORDER BY emp_id) AS row_num
    FROM employees
) paged
WHERE row_num BETWEEN 1 AND 5;

This query fetches the first 5 rows from the dataset.



Related Window Functions

Besides ROW_NUMBER(), SQL provides other useful ranking functions:

1. RANK()

Assigns the same rank to duplicate values, skipping subsequent ranks.

SELECT
    emp_id,
    department,
    salary,
    RANK() OVER(PARTITION BY department ORDER BY salary DESC) AS rank_num
FROM employees;

2. DENSE_RANK()

Similar to RANK(), but does not skip ranks for duplicate values.

SELECT
    emp_id,
    department,
    salary,
    DENSE_RANK() OVER(PARTITION BY department ORDER BY salary DESC) AS dense_rank_num
FROM employees;

3. NTILE(n)

Divides rows into n equal groups and assigns a group number.

SELECT
    emp_id,
    department,
    salary,
    NTILE(3) OVER(PARTITION BY department ORDER BY salary DESC) AS group_num
FROM employees;

When to Use ROW_NUMBER()

✅ Finding duplicate rows and removing them
✅ Selecting the nth highest or lowest value in a dataset
✅ Implementing pagination in SQL queries
✅ Assigning sequential numbers to rows for reporting


Conclusion

The ROW_NUMBER() OVER(PARTITION BY ...) function is a powerful SQL feature for ranking, filtering, and organizing data efficiently. By understanding this function and related ranking functions, you can significantly enhance your SQL querying skills.




Comments

All Categories

Call Fusion BIP Report2 Change Password1 Code Combinations2 Compute Instance2 CTE1 Customer1 Data Aggregation2 Database5 Date Conversion1 DB Adapter2 Decryption1 Development1 EBS4 Encryption1 ESS Jobs3 Examine1 FBDI3 Fusion APIs1 Fusion BIP7 GIT2 GL3 GL Journals1 GL_DAILY_CONVERSION_TYPES1 GL_DAILY_RATES1 ICS1 Identity Domain1 Integrations1 Java1 Journal Import1 Keys1 Legal Entity1 LookupTypeLOV1 LOV1 LOVs1 MultiPartAPIs1 Networking1 NVL2 NVL in OIC2 OCI11 OCI Billing1 OCI Compute5 OCI Cost Management1 OCI Events Service1 OCI Free Tier3 OCI Notifification Service1 OCI Security3 OIC4 OIC Mapper2 Oracle26 Oracle ADF17 Oracle APEX1 Oracle Apps59 Oracle Apps R126 Oracle ATP1 Oracle BIP8 Oracle Cloud12 Oracle Cloud Free Tier1 Oracle cloud Infrastructure9 Oracle Cloud Security2 Oracle Cloud VM1 Oracle DB4 oracle ebs5 Oracle ERP4 Oracle ERP Adapter2 Oracle ERP Cloud7 Oracle financials2 Oracle Forms1 Oracle Fusion57 Oracle Fusion BIP4 Oracle Fusion ERP17 Oracle Fusion Financials18 Oracle Integration Cloud3 Oracle OAF17 Oracle OCI14 Oracle OIC22 Oracle SOA 12c10 Oracle SQL17 Oracle VBCS1 Oracle VBS2 Oracle Visual Builder Cloud Service1 Oracle Visual Builder Studio2 Oracle Workflow Notifications1 Others10 Payables2 Payables Import1 Properties1 R121 Register BIP as ESS Job1 Reset Password1 Responsibility1 REST4 Security List1 Site Map1 SOAP2 SOAP API2 SOAP UI3 SQL16 SQL Functions3 SQL Queries14 SQL Query8 SQL Tips3 SSH1 TCA1 Value Sets1 VBCS1 Virtual Machine2 Virtual Machines1 XML1 XSLT1
Show more