Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat am I doing wrong when using RAND() in MS SQL Server 2005?
    primarykey
    data
    text
    <p>I'm trying to select a random 10% sampling from a small table. I thought I'd just use the RAND() function and select those rows where the random number is less than 0.10:</p> <pre><code>SELECT * FROM SomeTable WHERE SomeColumn='SomeCondition' AND RAND() &lt; 0.10 </code></pre> <p>But I soon discovered that RAND() always returns the same number! Reminds me of this <a href="http://xkcd.com/221/" rel="nofollow noreferrer">xkcd cartoon</a>.</p> <p><img src="https://imgs.xkcd.com/comics/random_number.png"></p> <p>OK, no problem, the RAND function takes a seed value. I will be running this query periodically, and I want it to give different results if I run it on a different day, so I seed it with a combination of the date and a unique row ID:</p> <pre><code>SELECT * FROM SomeTable WHERE SomeColumn='SomeCondition' AND RAND(CAST(GETDATE) AS INTEGER) + RowID) &lt; 0.10 </code></pre> <p>I still don't get any results! When I show the random numbers returned by RAND, I discover that they're all within a narrow range. It appears that getting a random number from RAND requires you to use a random seed. If I had a random seed in the first place, I wouldn't need a random number!</p> <p>I've seen the previous discussions related to this problem: </p> <p><a href="https://stackoverflow.com/questions/52964/sql-server-random-sort">SQL Server Random Sort</a><br> <a href="https://stackoverflow.com/questions/19412/how-to-request-a-random-row-in-sql">How to request a random row in SQL?</a></p> <p>They don't help me. TABLESAMPLE works at the page level, which is great for a big table but not for a small one, and it looks like it applies prior to the WHERE clause. TOP with NEWID doesn't work because I don't know ahead of time how many rows I want.</p> <p>Anybody have a solution, or at least a hint?</p> <p><strong>Edit:</strong> Thanks to AlexCuse for a <a href="https://stackoverflow.com/questions/163604/what-am-i-doing-wrong-when-using-rand-in-ms-sql-server-2005#163843">solution</a> which works for my particular case. Now to the larger question, how to make RAND behave?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload