Dense Rank SQL

Galaxy Glossary

How does the DENSE_RANK() function work in SQL?

DENSE_RANK() assigns ranks to rows within a partition based on a specified order, but without gaps in the ranking sequence. This is different from RANK() which allows gaps.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

The DENSE_RANK() function in SQL is a window function that assigns a rank to each row within a partition based on a specified order. It's crucial for scenarios where you need a continuous ranking without skipping numbers. Imagine you're ranking employees by salary within each department. If two employees have the same salary, DENSE_RANK() will assign them the same rank, and the next rank will be immediately after, without skipping any numbers. This is different from the RANK() function, which assigns ranks with gaps when there are ties. For example, if three employees share the same second-highest salary, RANK() would assign ranks 2, 2, and 2, then the next rank would be 5. DENSE_RANK() would assign ranks 2, 2, 2, and then 3. This continuous ranking is often useful for reporting and analysis.

Why Dense Rank SQL is important

DENSE_RANK() is important because it provides a continuous ranking, which is often necessary for reporting and analysis where you want to avoid gaps in the ranking sequence. This is particularly useful when comparing relative positions within groups.

Example Usage


CREATE TABLE SalesData (
    SalesPerson VARCHAR(50),
    SalesAmount DECIMAL(10, 2)
);

INSERT INTO SalesData (SalesPerson, SalesAmount) VALUES
('John Doe', 10000),
('Jane Smith', 12000),
('David Lee', 15000),
('Emily Brown', 12000),
('Michael Davis', 10000);

SELECT
    SalesPerson,
    SalesAmount,
    DENSE_RANK() OVER (ORDER BY SalesAmount DESC) AS SalesRank
FROM
    SalesData;

Common Mistakes

Want to learn about other SQL terms?