EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

SQL DENSE_RANK()

Home » Data Science » Data Science Tutorials » SQL Tutorial » SQL DENSE_RANK()

SQL DENSE_RANK()

Introduction to SQL DENSE_RANK()

DENSE_RANK() was introduced in SQL Server 2005 and it returns a rank that starts at 1 based on the ordering of the row and there is no gap in ranking values. So DENSE_RANK() returns a rank of the specific row which is one plus distinct rank values that have come before the specific row. The DENSE_RANK() is a window function that assign the rank to rows based on the current partition in the result. If the value is same for two rows then they will receive the same rank which is similar to RANK() which means if there are two rows at rank one and there are a total of four such rows then DENSE_RANK() will return 1,1,2,3 whereas RANK() would return 1,1,3,4.

The following shows the common syntax of a DENSE_RANK() in SQL Server:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

DENSE_RANK() OVER (
[PARTITION BY partition_expression, ... ] ORDER BY sort_expression [ASC | DESC], ...
)

The partitioning and order of rows is defined by OVER clause in a window and so they are called window function and following arguments are used in this clause:

  • ORDER BY – It defines the logical order of the rows
  • PARTITION BY – It divides the result into separate partitions and the window function is applied individually to every partition.

The return type of this function is bigint. DENSE_RANK() function is non-deterministic as opposed to deterministic functions which return the same result at any time. When this function is called it may return a different result at a different time even if the database state remains same.

Examples of SQL DENSE_RANK()

Let us discuss examples of SQL DENSE_RANK().

Example #1 – Creating table inserting rows and using DENSE_RANK()

CREATE TABLE dense_rank_tutorial(
alphabet VARCHAR(10)
);
INSERT INTO dense_rank_tutorial(alphabet) VALUES('A'),('B'),('B'),('C'),('C'),('D'),('E');
SELECT alphabet,
DENSE_RANK() OVER (ORDER BY alphabet) my_dense_rank
FROM dense_rank_tutorial;

The result set is as follows:

SQL DENSE_RANK() 1

We have created a table and inserted values then used the DENSE_RANK() to get the rank of the alphabets. We have ordered the ranking by alphabet. Since B and C are repeated, they have same rank, and since we are using dense rank functions so the ranks are not skipped and we use the distinct rank value that have came before B or C and then added 1 to get the ranks.

Example #2 – Simple example with DENSE_RANK()

SELECT emp_name,emp_gender,emp_salary,
DENSE_RANK() OVER (ORDER BY emp_salary desc) AS DenseRank
FROM Employee;

Popular Course in this category
JDBC Training (6 Courses, 7+ Projects)6 Online Courses | 7 Hands-on Projects | 37+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,676 ratings)
Course Price

View Course

Related Courses
PHP Training (5 Courses, 3 Project)Windows 10 Training (4 Courses, 4+ Projects)SQL Training Program (7 Courses, 8+ Projects)PL SQL Training (4 Courses, 2+ Projects)Oracle Training (14 Courses, 8+ Projects)

The result set is as follows:

SQL DENSE_RANK() 2

This is the basic example in which we select name, gender, and salary from Employee table and used DENSE_RANKfunction to get the rank of salary of each employee. As you can see average of Tom and Ron each has 9500so the rank is 1. Subsequently the ranksare calculated for the rest of the entries. Notice that Jodi has rank of 2 and not 3 since we have used dense rank. If we have used normal rank function then it would have skipped rank 2 and given rank 3 for Jodi.

Example #3 – Using DENSE_RANK() to find Nth highest salary

SELECT * FROM Employee ORDER BY emp_salary DESC

The result set is as follows:

SQL DENSE_RANK() 3

This gives the salary of all employees in descending order

WITH SalaryResult AS
(
SELECT emp_gender,emp_salary,emp_name,
DENSE_RANK() OVER (ORDER BY emp_salary desc) AS SalaryDenseRank
FROM Employee
)
SELECT TOP 1 emp_salary,emp_name FROM SalaryResult WHERE SalaryDenseRank = 1

The result set is as follows:

SQL DENSE_RANK() 4

Here we have used DENSE_RANK() to calculate the rank of salary of each employee. But we have wrapped it in a CTE(Common Table Expression) SalaryResult so we can use it in the next query.

The following shows the common syntax of a CTE in SQL Server if you are not familiar with it:

WITH expression_name[(column_name [,...])] AS
(CTE_definition)
SQL_statement;

So, in the subsequent query we have used SalaryResult CTE and returned the employee salary and name of the person whose dense rank is 1.

WITH SalaryResult AS
(
SELECT emp_gender,emp_salary,emp_name,
DENSE_RANK() OVER (ORDER BY emp_salary desc) AS SalaryDenseRank
FROM Employee
)
SELECT TOP 1 emp_salary,emp_name FROM SalaryResult WHERE SalaryDenseRank = 2

The result set is as follows:

SQL DENSE_RANK() 5

In this example we have written a similar query but in this case we have used second rank and we got the result using DENSE_RANK(). Instead if we have used RANK() then the result set will be empty as there is no second rank as we can see in full result set TOM and RON shares same salary.

Example #4 – Using DENSE_RANK() with PARTITION BY clause

SELECT emp_gender,emp_salary,emp_name,
DENSE_RANK() OVER (PARTITION BY emp_gender ORDER BY emp_salary desc) AS SalaryDenseRank
FROM Employee;

The result set is as follows:

example 4

In this, we have used DENSE_RANK() and partitioned the data using gender so now this function work within the window of the partition. Now we can use this to our advantage in the next query

WITH SalaryResult AS
(
SELECT emp_gender,emp_salary,emp_name,
DENSE_RANK() OVER (PARTITION BY emp_gender ORDER BY emp_salary desc) AS SalaryDenseRank
FROM Employee
)
SELECT TOP 1 emp_salary,emp_name,emp_gender FROM SalaryResult WHERE SalaryDenseRank= 3 and emp_gender ='Female'

The result set is as follows:

example 4-1

In this query we got the rankings from DENSE_RANK() and using a SQL CTE we get the result of a female employee with dense rank 3 and her name is Sara. This is achieved by partitioning the data according to gender to get the ranking of male and female employee separately.

Conclusion

Hopefully, now you know what DENSE_RANK() is in SQL server and how it is used to get the ranks from the values specified in a given column.

Recommended Articles

This is a guide to SQL DENSE_RANK(). Here we discuss Introduction, syntax, parameters, and Examples with code implementation. You can also go through our other related articles to learn more –

  1. MySQL Create Function
  2. MySQL encode()
  3. MySQL EXISTS
  4. MySQL DELETE Trigger

All in One Data Science Bundle (360+ Courses, 50+ projects)

360+ Online Courses

50+ projects

1500+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
SQL Tutorial
  • Functions
    • SQL Date Function
    • SQL String Functions
    • SQL Compare String
    • SQL Window Functions
    • SQL Timestamp
    • SQL TO_DATE()
    • SQL DATEADD()
    • ANY in SQL
    • LIKE Query in SQL
    • BETWEEN in SQL
    • LTRIM() in SQL
    • TOP in SQL
    • SQL Select Top
    • Merge SQL
    • SQL TRUNCATE()
    • SQL UNION
    • SQL ALL
    • SQL INTERSECT
    • SQL Alias
    • SQL Server Substring
    • CUBE in SQL
    • SQL RANK()
    • SQL CTE
    • SQL LAG()
    • SQL MID
    • SQL avg()
    • SQL WEEK
    • SQL DELETE
    • SQL DATEPART()
    • SQL DECODE()
    • SQL DENSE_RANK()
    • SQL NTILE()
    • SQL NULLIF()
    • SQL Stuff
    • SQL Ceiling
    • SQL EXISTS
    • SQL LEAD()
    • SQL ROW_NUMBER
    • SQL Server Replace
    • T-SQL INSERT
    • SQL Ranking Function
  • Basic
    • What is SQL
    • Careers in SQL
    • Careers in SQL Server
    • IS SQL Microsoft?
    • SQL Management Tools
    • What is SQL Developer
    • Uses of SQL
    • How to Install SQL Server
    • What is SQL Server
    • Database in SQL
    • SQL Data Types
    • SQL Keywords
    • Composite Key in SQL
    • SQL Constraints
    • Transactions in SQL
    • First Normal Form
    • SQL Server Data Types
    • SQL Administration
    • SQL Variables
    • Cheat sheet SQL
  • Operators
    • SQL Operators
    • SQL Arithmetic Operators
    • SQL Logical Operators
    • SQL String Operators
    • Ternary Operator in SQL
  • Commands
    • SQL Commands
    • SQL Alter Command
    • SQL Commands Update
    • SQL DML Commands
    • FETCH in SQL
  • Clause
    • SQL Clauses
    • SQL IN Operator
    • SQL LIKE Clause
    • SQL NOT Operator
    • SQL Minus
    • SQL WHERE Clause
    • SQL with Clause
    • SQL HAVING Clause
    • GROUP BY clause in SQL
    • ORDER BY Clause in SQL
    • SQL ORDER BY CASE
    • SQL ORDER BY DATE
    • SQL ORDER BY Alphabetical
    • SQL ORDER BY Ascending
    • SQL GROUP BY Month
    • SQL GROUP BY Multiple Columns
    • SQL GROUP BY DAY
    • SQL GROUPING SETS
  • Queries
    • SQL Insert Query
    • SQL SELECT Query
    • SQL SELECT RANDOM
    • SQL Except Select
    • SQL Subquery
    • SQL SELECT DISTINCT
    • SQL WITH AS Statement
  • Keys
    • SQL Keys
    • Primary Key in SQL
    • Foreign Key in SQL
    • Unique Key in SQL
    • Alternate Key in SQL
  • Joins
    • Join Query in SQL
    • Types of Joins in SQL
    • Types of Joins in SQL Server
    • SQL Inner Join
    • SQL Join Two Tables
    • SQL Delete Join
    • SQL Left Join
    • SQL Right Join
    • SQL Cross Join
    • SQL Outer Join
    • SQL Full Join
    • SQL Self Join
    • Natural Join SQL
    • SQL Multiple Join
  • Advanced
    • Aggregate Functions in SQL
    • IF ELSE Statement in SQL
    • SQL CASE Statement
    • SQL While Loop
    • SQL INSTR()
    • What is Procedure in SQL
    • Stored Procedure in SQL?
    • SQL Server Constraints
    • SQL DELETE ROW
    • Column in SQL
    • Table in SQL
    • SQL Virtual Table
    • SQL Merge Two Tables
    • SQL Table Partitioning
    • SQL Temporary Table
    • SQL Clone Table
    • SQL Rename Table
    • SQL LOCK TABLE
    • SQL Mapping
    • Cursors in SQL
    • AND in SQL
    • Wildcard in SQL
    • SQL FETCH NEXT
    • SQL Views
    • Triggers in SQL
    • SQL UPDATE Trigger
    • SQL AFTER UPDATE Trigger
    • SQL Update Statement
    • SQL DROP TRIGGER
    • Views in MySQL
    • SQL COMMIT
    • Distinct Keyword in SQL
    • PARTITION BY in SQL
    • SQL Set Operators
    • SQL UNION ALL
    • Metadata in SQL
    • SQL Bulk Insert
    • Array in SQL
    • SQL REGEXP
    • JSON in SQL
    • SQL For loop
    • EXPLAIN in SQL
    • SQL Cluster
    • SQL Backup
    • SQL Pattern Matching
    • SQL Users
    • ISNULL SQL Server
    • SQL Import CSV
  • Interview Questions
    • SQL Interview Questions
    • Advance SQL Interview Questions
    • SQL Joins Interview Questions
    • SQL Server Interview Questions

Related Courses

JDBC Training Course

PHP course

Windows 10 Training

SQL Course Training

PL/SQL Certification Courses

Oracle Certification Courses

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - JDBC Training Course Learn More