Sobes.tech
Middle

Tell me about the main ranking functions in Transact-SQL.

sobes.tech AI

Answer from AI

ROW_NUMBER() numbers the rows in the result set of a section, starting from 1 for the first row.

RANK() assigns a rank to each row within its section. If two or more rows have the same value in the ORDER BY expression, they are assigned the same rank, and the next rank is skipped.

DENSE_RANK() is similar to RANK(), but does not skip ranks when there are duplicate values.

NTILE(n) distributes the rows in a section into a specified number (n) of groups and assigns each row a group number (bucket), starting from 1.

-- Example of using ROW_NUMBER
SELECT
    ProductName,
    Price,
    ROW_NUMBER() OVER (ORDER BY Price) AS RowNum
FROM
    Products;

-- Example of using RANK
SELECT
    ProductName,
    Price,
    RANK() OVER (ORDER BY Price) AS RankNum
FROM
    Products;

-- Example of using DENSE_RANK
SELECT
    ProductName,
    Price,
    DENSE_RANK() OVER (ORDER BY Price) AS DenseRankNum
FROM
    Products;

-- Example of using NTILE
SELECT
    ProductName,
    Price,
    NTILE(4) OVER (ORDER BY Price) AS NtileGroup
FROM
    Products;
Function Description Skips Ranks with Duplicates
ROW_NUMBER() Assigns a unique sequential number to each row in the section. No
RANK() Assigns a rank to each row. Skips the next rank in case of duplicates. Yes
DENSE_RANK() Assigns a rank to each row. Does not skip ranks with duplicates. No
NTILE(n) Divides rows into n groups and assigns a group number. No
Tell me about the main ranking functions in… - sobes.tech