Greg's Blog

helping me remember what I figure out

How-to Retrieve a Random Record

| Comments

One of the features on our web site is the quote of the day. This quote is selected at random from the quote database. In order to be able to do this you have to use the RandRange function, which selects a random integer between two values. The first value is one as it represents the first record in the table and the second is the integer generated using the Count() function on the quote table. That way I make sure that no value is generated which is greater than the actual number of records stored. BTW this assumes that you don’t delete any records

Code:
<cfquery datasource=”MyDatasource” name=”CountQuoteID”>
Select Count(Quote_ID) as Total
From Quote
</cfquery>

Next I stored that result in a variable called TotalCount.

Code:
<cfoutput query=”CountQuoteID”>
<cfset TotalCount=#Total#>
</cfoutput>

Then I could proceed and create the RandRange function based on 1 and TotalCount, which is stored as RandFinal.

Code:
<cfset RandFinal=RandRAnge(1, #TotalCount#)>

This variable I use in my conditional query which retrives the actual quote where the unique identifier = RandFinal.

Code:
<cfquery datasource=”MyDatasource” name=”GetRandomQuote”>
Select Quote_Text
From Quote
Where quote_id = #RandFinal#
</cfquery>

Next all you need to do is Output the result in your page and format the output accordingly.

Code:
<cfoutput query=”GetRandomQuote”>
#Quote_Text#
</cfoutput>