Seeding SQL RAND() Method With NEWID() For Per-Row Random Values (Thanks Joshua Cyr)

Posted January 27, 2009 at 2:54 PM by Ben Nadel

Tags: SQL

From what I have read and from what I've seen demos of, I thought that MS SQL's RAND() method could only return one random value per connection. As I never looked at the documentation for RAND(), I never realized that it could be seeded. This morning, in my post on selecting random records from a weighted data table, Joshua Cyr pointed me to a great blog post demonstrating how to get RAND() to produce random numbers for each record in a query.

Before we see that, however, let's take a look at how it won't work:

  • <!--- Select random numbers. --->
  • <cfquery name="qRandom" datasource="#REQUEST.DSN#">
  • SELECT
  • p.id,
  • ( RAND() ) AS random_number
  • FROM
  • pivot1000 p
  • WHERE
  • p.id < 10
  • ORDER BY
  • p.id ASC
  • </cfquery>
  •  
  •  
  • <!--- Output the random numbers generated. --->
  • <cfloop query="qRandom">
  •  
  • #qRandom.random_number#<br />
  •  
  • </cfloop>

Notice here that we are simply selecting RAND() as a column in the table, then output that column. When we run this code, we get the following:

0.625088599784
0.625088599784
0.625088599784
0.625088599784
0.625088599784
0.625088599784
0.625088599784
0.625088599784
0.625088599784

Each call to RAND() produces the same result. This is because the RAND() method is implicitly seeded on the first call and then each subsequent call in the same connection uses the same seed value. To get a new random value for each RAND() method call, we have to pass it a new seed value each time.

The seed value must be numeric. Now, in the past, I've used NEWID() to create random numbers; but again, I never tried this on a per-row basis. As demonstrated in Josh's link, the NEWID() can be used to seed the RAND() method call every time it is run:

  • <!--- Select random numbers. --->
  • <cfquery name="qRandom" datasource="#REQUEST.DSN#">
  • SELECT
  • p.id,
  •  
  • <!--- Seed RAND() with binary version of NEWID(). --->
  • (
  • RAND(
  • CAST( NEWID() AS varbinary )
  • )
  • ) AS random_number
  • FROM
  • pivot1000 p
  • WHERE
  • p.id < 10
  • ORDER BY
  • p.id ASC
  • </cfquery>
  •  
  •  
  • <!--- Output the random numbers generated. --->
  • <cfloop query="qRandom">
  •  
  • #qRandom.random_number#<br />
  •  
  • </cfloop>

As I have stated before, I still don't know what the conversion from UUID to VARBINARY does exactly, but it produces are binary data structure that then get implicitly cast to a numeric value when passed to the RAND() method. As a result, this seeds the RAND() method with a new value on each row and gives us the following output:

0.632351429673
0.277469709628
0.291371676631
0.187895386945
0.0332443201662
0.269721718406
0.801980914521
0.984558916944
0.569620907931

A random value for each record. Good stuff! Thanks a lot Josh!




Reader Comments

Jan 27, 2009 at 8:42 PM // reply »
40 Comments

just in case you don't already know you can also use NEWID() to return random records from a table by using it in the ORDER BY clause:

ORDER BY NEWID()


Jun 23, 2009 at 12:12 PM // reply »
1 Comments

you are they man. Great idea of of unique row values selection.


Oct 7, 2009 at 1:25 PM // reply »
1 Comments

Thanks - this post helped me out :)


Sep 22, 2010 at 11:17 AM // reply »
1 Comments

This is awesome - most of the other details I read were all about creating functions and views, which is cool if you actually have that kind of access to the database. This helped me de-identify some Personal Information data by randomly adding/subtracting somewhere between 1-365 days to the date of birth. Thanks! :)


Sep 22, 2010 at 2:05 PM // reply »
11,314 Comments

@Chris,

Cool man, glad to help.


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Jun 19, 2013 at 9:52 PM
Working With Inherited Collections In AngularJS
I recognize the applicability of your solution, and how easy it makes to share data across multiple views or even "submodules" of rather simple application. But it seems to me that it creat ... read »
Jun 19, 2013 at 9:38 PM
Directive Link, $observe, And $watch Functions Execute Inside An AngularJS Context
@Alesei, Glad you like it. Even after working with AngularJS for months, I still get a bunch of unexpected, "$digest is already in progress". So hard to debug sometimes! ... read »
Jun 19, 2013 at 9:36 PM
Working With Inherited Collections In AngularJS
@Mike, The relationship of $scope values is definitely an interesting thing! But it's not simple - it really forces you to understand prototypal inheritance, which is not at all a simple topic! Gla ... read »
Jun 19, 2013 at 9:35 PM
Experimenting With The Amazon Simple Storage Service (S3) API Using ColdFusion
@Joe, Oh, super interesting! I had only thought to url-encode the signature; but I think that's because the S3 docs actually have a special NOTE telling you to do so. It would have never occurred t ... read »
Jun 19, 2013 at 9:32 PM
Experimenting With The Amazon Simple Storage Service (S3) API Using ColdFusion
@Richard, Glad you like! Hopefully I'll have some more interesting stuff coming. This morning, I blogged a bit more about generating the pre-signed, query string authenticated URLs; but, then deeme ... read »
Jun 19, 2013 at 9:31 PM
Filter vs. ngHide With ngRepeat In AngularJS
@Mike, Honestly, in the majority of cases, I would say there isn't going to be a difference. Both approaches have trade-offs. If you use the filter, then you have fewer DOM elements and fewer $scop ... read »
Jun 19, 2013 at 2:01 PM
Experimenting With The Amazon Simple Storage Service (S3) API Using ColdFusion
I have coincidentally been beating my head against the S3 API for the last week or so. One big "gotcha" I had to work around was file names and paths containing spaces. Remember to URL Enco ... read »
Jun 19, 2013 at 1:27 PM
Using Slice(), Substring(), And Substr() In Javascript
very good article. By the way IE supports negative values in substr or slice in verson 10. ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools