Chitika

Friday, September 28, 2012

Get Random Records from SQL Server

How to get random records from SQL Server based on Where Clause.
Let's say you have a database of customers and you initiated a contest wherein you determine the winners by randomly selecting 5 customers from your database.  How would you go about selecting 5 random records from your customers table?

In SQL Server, it is quite easy to do this thanks to the NEWID() system function.  The NEWID() system function creates a unique value of type uniqueidentifier.  There's no need to add a new column to your table just to have the ability of randomly selecting records from your table.  All that needs to be done is include the NEWID() system function in the ORDER BY clause when doing your SELECT statement. 


Syntax

Select Top [No. of Random Records you want]  *
from
(
Select  Col1, Col2
from ActualTableName
where
Col1 Like '%SearchWord%'
VirtualTable
ORDER BY NEWID()
Note: VirtualTable is table that doesn't exist in database, it is just a placeholder name.


Example
Select Top 1 *
from
(
Select QuestionId, QuestionTitle
from ForumQuestion
Where
ForumQuestion.QuestionTitle Like @SearchKeyword
) MyTable
ORDER BY NEWID()



No comments:

Post a Comment