Get Random records on each fetch using TABLESAMPLE TIP #34

 

As discussed in previous tip which is TIP #33 we can get random result set by using NEWID function.

Now same can be achieve by using one more option which is called TABLESAMPLE.

We have following syntax for it

SELECT * FROM tableName TABLESAME (Number ROWS/PERCENT)

For example I am using same Adventureworks database and fetching top 10 records from Person table which should be different each time.

So, I will write following select query 

SELECT TOP(10) FirstName,Lastname,MiddleName from Person.Person TABLESAMPLE(10 Percent)

OR

SELECT TOP(10) FirstName,LastName, MiddleName From Person.Person TABLESAMPLE(1000 Rows)

When , I run it I got following records.

tableSample

So this is another a way of  fetching random numbers.

Enjoy !!!

RJ

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s