Monday, April 11, 2011

Generate Random Numbers

QL 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.
To use it, you can simply do a simple SELECT, as follows:
SELECT RAND() AS [RandomNumber]
The result generated by this SELECT statement is as follows (note that your results may be different from the value shown here, hence the name random)
The output of the RAND function will always be a value between 0 and 1.  If you want to generate a random integer number, all you have to do is multiply it by the maximum value you want generated and then get rid of the decimal places.  One way of getting rid of the decimal places is by CASTing it to INT.  Here's an example of generating a random number with a maximum value of 999,999:
SELECT CAST(RAND() * 1000000 AS INT) AS [RandomNumber]
And here's an example result of this SELECT statement:

The Downside of the RAND Function
One thing to take note with the RAND function is that if the seed parameter is passed to it, the output will always be the same.  This can be seen with the following:
SELECT RAND(1) AS [RandomNumber]
Running this SELECT statement multiple times with 1 as the seed of the RAND function will always yield the same result:
Another thing to take note with the RAND function is that if it is included in a SELECT statement on a table, the value returned for each row will be the same, as can be seen with the following example.
SELECT TOP 10 RAND() AS [RandomNumber], [CustomerID], [CompanyName], [ContactName]
FROM [dbo].[Customers]
RandomNumber         CustomerID CompanyName                         ContactName
-------------------- ---------- ----------------------------------- -------------------
0.21090395019612362  ALFKI      Alfreds Futterkiste                 Maria Anders
0.21090395019612362  ANATR      Ana Trujillo Emparedados y helados  Ana Trujillo
0.21090395019612362  ANTON      Antonio Moreno Taquería             Antonio Moreno
0.21090395019612362  AROUT      Around the Horn                     Thomas Hardy
0.21090395019612362  BERGS      Berglunds snabbköp                  Christina Berglund
0.21090395019612362  BLAUS      Blauer See Delikatessen             Hanna Moos
0.21090395019612362  BLONP      Blondesddsl père et fils            Frédérique Citeaux
0.21090395019612362  BOLID      Bólido Comidas preparadas           Martín Sommer
0.21090395019612362  BONAP      Bon app'                            Laurence Lebihan
0.21090395019612362  BOTTM      Bottom-Dollar Markets               Elizabeth Lincoln