Click here to Skip to main content
Licence 
First Posted 2 Mar 2005
Views 74,206
Bookmarked 42 times

How to make a random selection from an SQL table

By | 2 Mar 2005 | Article
A simple technique for selecting random records from a table.
 
Part of The SQL Zone sponsored by
See Also

Introduction

This is one of the simplest solutions to a difficult problem I have ever come across. If like me, you have ever had the need to randomly select a number of database records from an SQL server (e.g. for banner ads or special offer selections) then this is an easy solution.

Solution

OK. So you have a table of records in an SQL database. Let's call the table "tbl_offers" for this example. In SQL you can assign a new ID value to any record which you select using the function "NewID()". This means if you order your records by this randomly generated ID field and select the top five or ten say, then every time you will get a different set of results.

Code

Please note I have written the following code only to demonstrate the use of the SQL and so have made it as simple as possible.

//This table can subsequently be used as a datasource
DataTable tbl_offers = new DataTable();

SqlConnection conn_offers = new SqlConnection(
    "Insert your DB Connection string here"
    );
SqlDataAdapter da_offers = new SqlDataAdapter(
     "SELECT Top 5 * FROM tbl_offers ORDER BY NewID()", 
      conn
    );
da_offers.Fill(tbl_offers);

And that's it. Very simple, very effective.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Ach1lles

Founder
Tech Dept
United Kingdom United Kingdom

Member

My Evolution:
TRS-80 Basic, Clipper, C, Better Basic, FORTRAN, C++, Visual Basic, Delphi, C#


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralLove it, Take 5 PinmemberOmar Gamil4:06 18 Jun '11  
Generaltrying to retrieve random questions from SQL Server PinmemberMember 445285319:51 20 Feb '10  
Generaltrying to retrieve random questions from SQL Server PinmemberMember 445285319:43 20 Feb '10  
GeneralCool tip Pinmemberaries781121:16 2 Aug '09  
GeneralAmazing PinmemberMember 337127416:53 4 Feb '09  
GeneralGood idea but doesn't work on all servers PinmemberMegosAR20:53 16 Oct '07  
GeneralYou can do the same using Rand function right !! PinmemberHimanshu Kumar Sinha23:07 11 Jun '06  
GeneralFantastic But............ Pinmemberyasir102420:58 23 May '06  
GeneralGreat! Pinmembertakcrazy2:31 26 Apr '06  
GeneralBrilliant Pinmemberfurioso11:18 12 Mar '06  
QuestionFascinating -- where documented? Pinmemberdavidw880118:00 28 Mar '05  
AnswerRe: Fascinating -- where documented? Pinmemberdavidw880118:02 28 Mar '05  
Questionperformance hit? PinmemberAshley van Gerven12:55 4 Mar '05  
AnswerRe: performance hit? PinsussStephen R5:04 5 Mar '05  
AnswerRe: performance hit? PinmemberRafael Araújo13:06 23 Mar '05  
I wrote this solution that is considerable faster then the NewID() solution but has no flexibility and is based on tables with int primary keys (the ideal is an identity primary key).
If you dont need to make joins with other tables or other kinds of filters and, like me, always have identity primary keys, it will fit in most cases
 
Usage Examples (not good examples since 'Northwind..Products' only has 77 rows): :->
--return 100 random rows in a random order with all Products columns
exec spGetRandomRows 'Northwind..Products','ProductID'
 
--return 1000 random rows in a random order with columns ProductID,ProductName
exec spGetRandom 'Northwind..Products', 'ProductID', 1000, 'ProductID,ProductName'
 
--return 1000 random rows with columns ProductID, SupplierID, ProductName ordered by SupplierID and ProductName
exec spGetRandomRows 'Northwind..Products', 'ProductID', 1000, 'ProductID,SupplierID,ProductName', 'SupplierID,ProductName'
 

create proc spGetRandomRows
@source_table sysname,
@source_key sysname,
@return_count bigint = 100,
@return_columns varchar(200) = '',
@return_order varchar(200) = ''
as
 
set nocount on
 
select
@return_columns = case when len(@return_columns) > 0 then @return_columns else @source_table+'.*' end,
@return_order = case when len(@return_order) > 0 then ' order by '+@return_order else ' order by f.the_random_order' end
 
declare @sql varchar(8000)
 
if @return_count > 0
begin
set @sql = '
declare @i bigint, @count bigint, @return_count bigint
select @i = 0, @return_count = '+convert(varchar(20),@return_count)+'
 
declare @the_random_keys table(the_random_key bigint, the_random_order bigint identity(1,1) primary key)

declare @the_max_key table(the_max_key float, the_row_count bigint)

insert into @the_max_key(the_max_key,the_row_count) select max('+@source_key+'), count(*) from '+@source_table+'

select @return_count = case when @return_count < the_row_count then @return_count else the_row_count end from @the_max_key

while @i < @return_count
begin
declare @the_random_key bigint
while @the_random_key is null
select top 1 @the_random_key = o1.'+@source_key+' from '+@source_table+' o1 with(nolock)
where '+@source_key+' >
(select rand() * the_max_key from @the_max_key)
and o1.'+@source_key+' not in (select the_random_key from @the_random_keys)
 

insert into @the_random_keys(the_random_key)values(@the_random_key)
set @the_random_key = null

set @i = @i + 1
end

select '+@return_columns+' from '+@source_table+' with(nolock)
inner join @the_random_keys f on f.the_random_key = '+@source_table+'.'+@source_key
+@return_order
exec(@sql)
end
else
select null
Generalgr8! PinmemberAssaad Codoholic20:17 2 Mar '05  
GeneralNice tip! - more info here... PinmemberRayD5:59 2 Mar '05  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120528.1 | Last Updated 2 Mar 2005
Article Copyright 2005 by Ach1lles
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid