Skip to content
Advertisement

Generate random numbers in a specific range without duplicate values

SELECT CEILING (RAND(CAST(NEWID() AS varbinary)) *275) AS RandomNumber

This creates random numbers. However, it spits out duplicates

Advertisement

Answer

In the comments to my other answer, you write:

The table I’m working with has an ID , Name , and I want to generate a 3rd column that assigns a unique random number between 1-275 (as there are 275 rows) with no duplicates.

In the future, please include details like this in your original question. With this information, we can help you out better.

First, let’s make a sample of your problem. We’ll simplify it to just 5 rows, not 275:

create table #data (
    id int,
    name varchar(10)
);

insert #data values 
    (101, 'Amanda'), 
    (102, 'Beatrice'), 
    (103, 'Courtney'),
    (104, 'Denise'),
    (105, 'Elvia');

Let’s now add the third column you want:

alter table #data add rando int;

Finally, let’s update the table by creating a subquery that orders the rows randomly using row_number(), and applying the output the the column we just created:

update  reordered
set     rando = rowNum
from    (
            select      *, 
                        rowNum = row_number() over(order by newid())
            from        #data
        ) reordered;

Here’s the result I get, but of course it will be different every time it is run:

select      *
from        #data

| id  | name     | rando |
+-----+----------+-------+
| 101 | Amanda   |   3   |
| 102 | Beatrice |   1   |
| 103 | Courtney |   4   |
| 104 | Denise   |   5   |
| 105 | Elvia    |   2   |
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement