7.1 Ranking Functions
7.1 Ranking Functions
1. ROW_NUMBER()
2. RANK()
3. DENSE_RANK()
NOTE: In the above syntax Partition by clause is optional and over() clause and order by clauses are
mandatory.
ROW_NUMBER(): This function returns serial number to every row irrespective of duplicates values.
Here FROM clause takes all data (all columns and all rows) from EMP table and ORDER BY clause sorts
the data in ascending order based on SAL column and ROW_NUMBER() function gives serial numbers to
each and every row and this serial number column we named as ROW_NUM and finally SELECT displays
ENAME DEPTNO and SAL along with new column ROW_NUM.
Execution Steps:
FROM
ORDER BY
ROW_NUMBER()
SELECT
Here FROM clause takes all data(all columns and all rows) from EMP table and PARTITION BY clause
divides the table into small partitions based on the DEPTNOs and ORDER BY clause sorts the data of each
partitions, that means each partition starts sorting order from 1. ROW_NUMBER() function gives serial
numbers to each partition. Finally SELECT displays ENAME, DEPTNO,SAL and ROW_NUM columns
Execution Order:
FROM
PARTITION BY
ORDER BY
ROW_NUMBER()
SELECT
RANK(): This function gives same rank for duplicate values and also gives gaps between ranks.
Here FROM clause takes all data(all columns and all rows) from EMP table. Order by clause keeps the
data in sorting order and RANK() gives numbers to the every row but it gives same number for duplicate
values and also gives gaps
Exectio Order:
FROM
ORDER BY
RANK()
SELECT
Execution Order:
FROM
PARTITION BY
ORDER BY
RANK()
SELECT
DENSE_RANK(): This function gives same rank for duplicate values and does not give gaps between
ranks.
Here FROM clause takes the data from EMP table and ORDER BY clause keeps the data in sorting order
based on SAL column. Dense_Rank() gives numbers to the sorted data and it gives same number to
duplicate values but it does not give gaps. This new column is named as DEN_RANK. Finally SELECT
displays ENAME, DEPTNO, SAL and DEN_RANK columns.
Execution Steps:
FROM
ORDER BY
DENSE_RANK()
SELECT
OUTPUT:
ENAME DEPTNO SAL DEN_RANK
MILLER 10 1300.00 1
CLARK 10 2450.00 2
KING 10 5000.00 3
SMITH 20 800.00 1
ADAMS 20 1100.00 2
JONES 20 2975.00 3
SCOTT 20 3000.00 4
FORD 20 3000.00 4
JAMES 30 950.00 1
WARD 30 1250.00 2
MARTIN 30 1250.00 2
ALLEN 30 1300.00 3
TURNER 30 1300.00 3
BLAKE 30 2850.00 4
Here FROM clause takes all data(all columns and all rows) from EMP table and PARTITION BY clause
divides the data into small partitions based on the DEPTNOs. ORDER BY clause keeps the data of each
partition in sorting order. DENSE_RANK() gives numbers for each partition starting from 1 and it also
gives same number for duplicate values and does not give gaps.