Tag: t-sq;. syndicated

  • RANK() vs DENSE_RANK(): #SQLNewBlogger

    Recently I had a question asked about why someone choose DENSE_RANK() vs RANK(). This was an analyst trying to decide how to produce a report, and I spent a few minutes helping them. This is a great, basic post on how this works and why I’d choose one.

    Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.

    The Scenario

    I wrote a question on this topic, and I’ll explain it in more detail. First, the setup. We’ll create a table and add some data.

    CREATE TABLE dbo.BlackFridaySales
    (
        Product NVARCHAR(50) NOT NULL PRIMARY KEY,
        Units   INT          NOT NULL
    );
    
    INSERT INTO dbo.BlackFridaySales (Product, Units)
    VALUES (N'55" TV',          900),
           (N'Air Fryer',       500),
           (N'Noise-Cancel Headphones', 500),
           (N'Robot Vacuum',    300);

    Next, let’s query the table and rank the sales. If we look above, we see that the product were inserted in the sales order, so the TV had the most units and the vacuum the least. We’d expect a ranking like this:

    1. TV
    2. Air Fryer
    3. Noise-Cancel Headphones
    4. Robot Vacuum

    Except, how do we rank the middle 2? Those had the same sales. If you reported this orally to someone, would you rank them as 1, 2, 3, with 2 items at 2? Are they 1, 2, 2, 4? Something else?

    Let’s look at T-SQL.

    Rank

    RANK() will produce the results that work like the placing in a race. If two people tie at second place, third place is lost and the next person gets fourth. Lots of sports work as RANK() does, with a result of 1, 2, 2, 4.

    2026-11_0345

    In this case, we would have to decide somehow which is 2nd and which 3rd, or leave them as 2nd in a report. After all, with 4 items, there are four places to fill.

    DENSE_RANK

    As the name implies, DENSE_RANK() closes of the orders and creates a more “dense” ranking. The results below show the ties, and then start sequencing with the next number, 3. The resultant ranking is 1, 2, 2, 3.

    2026-11_0346

    Less useful for competition, DENSE_RANK is more of a keeping things in a sequential order type of function. This is more useful for things where a discontinuity is a problem. Think sales promotions or other “brackets” of data. For these, we don’t want to skip numbers.

    SQL New Blogger

    I spent a few minutes trying to help someone to solve this, and I mocked a few things up. Taking that mock and then writing around it took me about 10 minutes to clean up some code, and then about 10 minutes to write the post.

    This is an easy way to showcase why you might make a choice, and why/how you might guide an AI. Try putting together a post on how you’re guide and evaluate an AI in a similar scenario. Maybe add some testing around this.