Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fill a column with random numbers in SQL? I get the same value in every row

Tags:

sql-server

UPDATE CattleProds
SET SheepTherapy=(ROUND((RAND()* 10000),0))
WHERE SheepTherapy IS NULL

If I then do a SELECT I see that my random number is identical in every row. Any ideas how to generate unique random numbers?

like image 446
NibblyPig Avatar asked Feb 15 '11 11:02

NibblyPig


People also ask

How do I assign a random number to each row in SQL?

Generating random numbers is very simple in SQL Server. We can use the built-in function RAND() to generate random number.

How do I assign a random number to a column in SQL?

SQL Server has a built-in function that generates a random number, the RAND() mathematical function. The RAND math function returns a random float value from 0 through 1. It can take an optional seed parameter, which is an integer expression (tinyint, smallint or int) that gives the seed or start value.

How to generate random number between two numbers in SQL Server?

In SQL Server there is a built-in function RAND() to generate random number. RAND() will return a random float value between 0 to 1. Usage RAND() As It Is. If you use RAND() as it is or by seeding it, you will get random numbers in decimals ranging between 0 and 1. Generate Integer Random Number Between Two numbers.

What is select random in SQL Server?

Introduction to SQL SELECT RANDOM. SQL Random function is used to get random rows from the result set. We use random function in online exams to display the questions randomly for each student. The usage of the SQL SELECT RANDOM is done differently in each database. Let us check the usage of it in different database.

How to randomly fill values from a given list in Excel?

To randomly fill values from a given list of data in Excel, we can apply the RANDBETWEEN function and VLOOKUP function to get it done as follows: Step 1: Right click the column of given list, and select Insert from right-clicking menu. Step 2: In the inserted column, type NO. as column heading, and ...

How to get random rows in postgre MySQL?

n MYSQL we use the RAND () function to get the random rows from the database. In postgre sql the representation of the random function is similar to the SQL. In MYSQL we use the RAND () function to get the random rows from the database. How to Implement SQL SELECT RANDOM? Let us implement the usage of the Random in the SQL.


3 Answers

Instead of rand(), use newid(), which is recalculated for each row in the result. The usual way is to use the modulo of the checksum. Note that checksum(newid()) can produce -2,147,483,648 and cause integer overflow on abs(), so we need to use modulo on the checksum return value before converting it to absolute value.

UPDATE CattleProds
SET    SheepTherapy = abs(checksum(NewId()) % 10000)
WHERE  SheepTherapy IS NULL

This generates a random number between 0 and 9999.

like image 168
Andomar Avatar answered Oct 13 '22 05:10

Andomar


If you are on SQL Server 2008 you can also use

 CRYPT_GEN_RANDOM(2) % 10000

Which seems somewhat simpler (it is also evaluated once per row as newid is - shown below)

DECLARE @foo TABLE (col1 FLOAT)

INSERT INTO @foo SELECT 1 UNION SELECT 2

UPDATE @foo
SET col1 =  CRYPT_GEN_RANDOM(2) % 10000

SELECT *  FROM @foo

Returns (2 random probably different numbers)

col1
----------------------
9693
8573

Mulling the unexplained downvote the only legitimate reason I can think of is that because the random number generated is between 0-65535 which is not evenly divisible by 10,000 some numbers will be slightly over represented. A way around this would be to wrap it in a scalar UDF that throws away any number over 60,000 and calls itself recursively to get a replacement number.

CREATE FUNCTION dbo.RandomNumber()
RETURNS INT
AS
  BEGIN
      DECLARE @Result INT

      SET @Result = CRYPT_GEN_RANDOM(2)

      RETURN CASE
               WHEN @Result < 60000
                     OR @@NESTLEVEL = 32 THEN @Result % 10000
               ELSE dbo.RandomNumber()
             END
  END  
like image 26
Martin Smith Avatar answered Oct 13 '22 04:10

Martin Smith


While I do love using CHECKSUM, I feel that a better way to go is using NEWID(), just because you don't have to go through a complicated math to generate simple numbers .

ROUND( 1000 *RAND(convert(varbinary, newid())), 0)

You can replace the 1000 with whichever number you want to set as the limit, and you can always use a plus sign to create a range, let's say you want a random number between 100 and 200, you can do something like :

100 + ROUND( 100 *RAND(convert(varbinary, newid())), 0)

Putting it together in your query :

UPDATE CattleProds 
SET SheepTherapy= ROUND( 1000 *RAND(convert(varbinary, newid())), 0)
WHERE SheepTherapy IS NULL
like image 12
Segev -CJ- Shmueli Avatar answered Oct 13 '22 05:10

Segev -CJ- Shmueli