Tag: SQLNewBlogger

  • 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.

  • Should You Use CHOOSE(): #SQLNewBlogger

    I was experimenting with CHOOSE() recently after I was asked a question. In a previous post, I found it can take a (ridiculous) number of arguments. In this post, I’ll look more practically at how this works and where you might use it.

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

    The Setup

    Let’s create a quick table with some data. In this case, I’ll create a table that stores some customer data. I’ll store a customer name and status in this table. There could be other data, but this shows the important parts.

    CREATE TABLE dbo.Customer ( [CustomerID] int, [CustomerName] varchar(200), [CustomerStatus] int )
    
    INSERT INTO dbo.Customer ([CustomerID], [CustomerName], [CustomerStatus])
    VALUES
    ( 1, 'Steve', 1 ),
    ( 2, 'Andy ', 1 ),
    ( 3, 'Brian', 1 ),
    ( 4, 'Allan', 0 ),
    ( 5, 'Devin ', NULL )
    

    This is something I’ll typically see a developer do, where they assume the customer status can be inferred. In this case, we’ll assume that:

    • 0 = inactive
    • 1 = active

    This doesn’t handle NULL, but a lot of people might choose (no pun intended) to make this a 0.

    Querying for Status

    If we want to present something readable, we might do this:

    SELECT CustomerID,
           CustomerName,
           CASE
               WHEN CustomerStatus = 0 THEN
                   'Inactive'
               WHEN CustomerStatus = 1 THEN
                   'Active'
               ELSE
                   'Inactive'
           END AS CustomerStatus
    FROM dbo.Customer;
    
    

    That works, but it’s a bit cumbersome. Since 2012, we’ve had CHOOSE(), which makes this smoother. The new code would be:

    SELECT CustomerID,
           CustomerName,
           CHOOSE(CustomerStatus, 'Inactive', 'Active') AS CustomerStatus
    FROM dbo.Customer;
    
    

    This doesn’t work great, as CHOOSE() is 1-based. This would return (I included the int value):

    2026-10_0136

    A better solution would be to add 1 to the value. This gives me new code:

    2026-10_0137

    Better, but not great. Instead, I’d want to enclose this and handle the NULL.

    2026-10_0138

    That works, but it’s not great. In general, I don’t like this use of coding CHOOSE() as it’s essentially hard coding values.

    Instead, I would lean towards a lookup table with statuses, especially because someone might want to change this later. I’d prefer that a join to a table is better than hard coding these values.

    Where to use CHOOSE()

    To me, the best use of CHOOSE is with boolean or bit values. In this case, we store a 1 or 0, but we can’t easily convert these. The best way to handle this for display, is something like this. Suppose I have a table of answers for users that have bit values. Something like this:

    CREATE TABLE dbo.Answers ( [QuestionID] INT, UserID INT, [Answer] bit)
    
    INSERT INTO dbo.Answers
    (
        QuestionID,
        UserID,
        Answer
    )
    VALUES
    ( 1, 1 , 1 ),
    ( 2, 1 , 1 ),
    ( 1, 2, 1 ),
    ( 2, 2, 0 ),
    ( 1, 3, 0 ),
    ( 1, 3, 0 )
    
    

    If I want to query this, I can use the technique above and get my true/false values.

    2026-10_0139

    There is no chance this will be extended or changed. Booleans only store 2 values. Of course, I might want to wrap this to handle NULLs if those are allowed.

    SQL New Blogger

    This post took me about 15 minutes to setup and write. The code was simple, and the explanation was easy. However, thinking where CHOOSE() would work well and not be a design issue later took me about 10 minutes of thinking and searching a bit on the Internet.

    Lots of people show CHOOSE() in a way that I disagree with, and really booleans only made sense to me.

    This showcases my thoughts, an opinion, and an idea. Show how you can think, especially in the age of AI and impress a potential interview team.

  • The #MS_DatabaseConnector## Role: #SQLNewBlogger

    I had seen these roles in various instances, but never dug into the new Fixed Server roles added to SQL Server. They are supposed to help ensure the principle of least privilege is followed.

    In this post, I look at one of these, the ##MSDatabaseConnector## role.

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

    Users and Logins

    This role is a new one that contains very narrow permissions. It allows a login to connect to any database without requiring a user account mapping. Typically if I create a login for “Steve”, I also create a User in a database that maps here. The convention for most people is to create a user “Steve” that links to the login “Steve”. Typically this is with code like:

    CREATE LOGIN [Steve]
    WITH PASSWORD = N'asdfasdf' MUST_CHANGE,
         DEFAULT_DATABASE = [master],
         CHECK_EXPIRATION = ON,
         CHECK_POLICY = ON;
    GO
    USE [sandbox];
    GO
    USE [Westwind];
    GO
    USE [AdventureWorks];
    GO
    CREATE USER [Steve] FOR LOGIN [Steve];

    NOTE: This isn’t the real password.

    Note 2: Don’t use passwords like this

    NOTE 3: Don’t skip the checks.

    Here I am mapping a user to a login, and while the name is the same, these are different objects. If I want the user, Steve, to have access to objects in AdventureWorks, I need to grant rights, or add the user to a Role.

    I could also do this:

    USE [sandbox] GO CREATE USER [Stephan] FOR LOGIN [Steve] GO

    
    

    In the Sandbox database, there is no User Steve. Instead, you can see below from SSMS that there is a different user here. My database has no “Steve” in the users, but “Stephan” is mapped to the login Steve.

    2026-09_0090

    The Login properties shows this as well.

    2026-09_0091

    I added a new user with this fixed server role, and no other database mappings. Here is the server role:

    2026-09_0093

    And the user mappings (trust me these are all blank)

    2026-09_0094

    I then logged in with this user to the AdventofCode database. As you can see, there are no users here for this login.

    2026-09_0095

    The login can connect, however, and I see the current user as the login name.

    2026-09_0097

    What can the user do? Well, he can’t access this table, 2021.Day1.

    2026-09_0098

    He can access schemas, which I saw with SQL Prompt Intellisense. That makes sense as the sys.schemas dmv is open to the public.

    2026-09_0099

    I granted rights to public for one table.

    2026-09_0100

    The login (or user with public) can query this.

    2026-09_0112

    If I check permissions for the login, I don’t see anything in the database other than basic things: connect, view CEK, view DMK.

    2026-09_0113

    This is interesting. It’s like a pseudo-user has been created for this session, mapped to the login. I’m not sure if this is correct or intended, but it’s what I’ve observed.

    I don’t know how useful this permission is, though I’m sure someone has a use case where they want something like a monitoring system, or maybe a pen-test available to check what a public user can see in every database.

    SQL New Blogger

    While I was investigating this role, over the course of testing a few things in 10-15 minutes, I sketched this post. I then spent another 20 minutes capturing some code and screenshots to see how things work.

    This is a good post of evaluating how things work and better understanding the system. I could use this as guidance, and perhaps tell an AI whether this role is useful or not. Or to avoid it.

    Write your own post, maybe even using AI to help you learn about this role or others. Those skills will help you in the future and you can showcase them for others.

  • Experimenting with CHOOSE: #SQLNewBlogger

    I was looking over the CHOOSE() function while editing an article at SQL Server Central. I realized there isn’t a documentation note on how many parameters can be included. I decided to test.

    This post looks at the tests and results.

    Tl;dr It appears 3925 is the most arguments.

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

    Building a Script

    Since I want to know where things fail, I decided to make a short T-SQL script that tests increasing numbers of parameters. This script builds a dynamic CHOOSE() select using a number of parameters and then loops for a set number of times, adding 1 parameter each time.

    SET NOCOUNT ON; DECLARE @MaxValues int = 5150; -- largest number of CHOOSE value arguments DECLARE @n int = 300; -- current number of value arguments DECLARE @i int; DECLARE @idx int; DECLARE @args nvarchar(max); DECLARE @sql nvarchar(max); WHILE @n <= @MaxValues BEGIN -- Build value list: 'Value 1', 'Value 2', ... 'Value n' SET @args = N''; SET @i = 1; WHILE @i <= @n BEGIN SET @args += CASE WHEN @i > 1 THEN N', ' ELSE N'' END + N'N''V' + CAST(@i AS nvarchar(10)) + N''''; SET @i += 1; END; -- Random index in 1..n (CHOOSE is 1-based; out of range returns NULL) SET @idx = ABS(CHECKSUM(NEWID())) % @n + 1; SET @sql = N'SELECT ' + CAST(@n AS nvarchar(10)) + N' AS ArgCount, ' + CAST(@idx AS nvarchar(10)) + N' AS PickedIndex, ' + N'CHOOSE(' + CAST(@idx AS nvarchar(10)) + N', ' + @args + N') AS Result;'; PRINT @sql; -- show the generated statement EXEC sys.sp_executesql @sql; -- run it SET @n += 1; END;


    This returns the command run. For the first 2 values of n, setting @n to 1 and @max to 2, I get this:

    SELECT 1 AS ArgCount, 1 AS PickedIndex, CHOOSE(1, N'V1') AS Result;
    SELECT 2 AS ArgCount, 1 AS PickedIndex, CHOOSE(1, N'V1', N'V2') AS Result;

    This let me test different values. I tried various values and eventually got this error:

    2026-09_0159

    I tried this a few different times, disconnecting and reconnecting and it seemed that I could get the number of parameters up to 3925. It failed sometimes at 3924 and sometimes at 3925.

    I’ve submitted a PR to add the max number to the docs, but it appears CHOOSE() works at a level that would cover lots of items. I see this as a small syntactic sugar add, and if I really needed to index 1000 entries, a join with a reference table would be a better choice.

    SQL New Blogger

    This script took a few minutes to write, but the testing took about 45 minutes. I was running this in the background with different values. 1..256, 255..1024, etc. I noticed that SSMS responded slower, so I started jumping to small ranges at large values to find the error.

    This post took me about 20 minutes to put together after the testing, which included the PR for Microsoft. This is an easy way to show that you can examine possibilities and find the limits of your code. That helps us decide how scalable or robust our solutions are.

    You could write this post and impress an interviewer. Choose your own T-SQL function and run an experiment.