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 »
34 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 »
10,640 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
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 10, 2012 at 7:21 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
Update! Instead of $(eval(options.insertAfter)).after(data['insertData']); I now use: var ajaxNode = document.createElement('span'); var parent = $(eval(options.insertAfter))[0].parentNode; ... read »
Feb 10, 2012 at 6:18 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
encountered this same, what I consider, jQuery bug last week. I'm building a site in which I load some content via AJAX. This content contains Linkedin share button placeholders which Linkedin API ne ... read »
Feb 10, 2012 at 11:30 AM
Cross-Origin Resource Sharing (CORS) AJAX Requests Between jQuery And Node.js
After you understand the concepts here, this is an awesome cheatsheet for enabling CORS in just about anything http://enable-cors.org/ ... read »
JM
Feb 10, 2012 at 9:10 AM
My Safari Browser SQLite Database Hello World Example
@Amy, Here is a very good tutorial on how to use JOIN: http://www.sqltutorial.org/sqljoin-innerjoin.aspx ... read »
Feb 10, 2012 at 4:42 AM
Building A Twitter-Inspired RESTful API Architecture In ColdFusion
This is great, very useful Ben. I spotted a small typo in the api.cgm listing: <cfthrow type="Unauthroized" /> Cheers Stefan ... read »
Feb 9, 2012 at 10:35 PM
CFDirectory Filtering Uses Pipe Character For Multiple Filters (Thanks Steve Withington)
I was wondering if there would be a filter you could apply so that you got everything but what you included in the filter. As in show me all docs that are not a .pdf. ... read »
Feb 9, 2012 at 10:29 PM
Learning ColdFusion 9: Application-Specific Data Sources
@Ben, No offence, but if people were really wanting advanced features they would be using a platform like ASP.NET MVC. CFML is so structurally compromised as a tag-based scripting language that ... read »
Feb 9, 2012 at 10:03 PM
Subversion - Cleanup Failed To Process The Following Paths
@Leviaguirre, do you still have problems with this? ... read »