All Pumped Up!

Hi and thanks for visiting! If this is your first visit to All Pumped Up!, It is strongly recommended that you Subscribe to the Site Feed for instant updates or join the APU! Newsletter for Email Updates.


How to Generate Random Records from any table in a database?

by SuperRaJJ on Mar.19, 2007, under Programming, SQL Server


Email Article Email Article Print Article Print Article 29 views

GD Star Rating
loading...

Ok guys, here’s a tech article for your reading pleasure. Actually while I was working on a project, the client asked me to randomly select some percentage of the total records of a table! I was a little puzzled since I didn’t do this before. But what better than do it the first time. The first time is the best time actually! ;)

Anyway, I did find some information on this on the net after searching about it. So I decided to write an article on it right here in my blog.

The trick involves using the NEWID() function of Microsoft SQL Server (verion 7 and above)

Ok, suppose if you want to select 10 percent of the total records in a given table, here is how you will select it:

SELECT TOP [x] PERCENT [COL1,COL2 ... COLn] FROM [TABLE_NAME] WHERE [COLx = 'SOME CONDITION'] ORDER BY NEWID(), [COL1,COL2 ... COLn]

( Where TOP [x] PERCENT represents the percent of the total records of the table that you want to select. [COL1,COL2 ... COLn] represents the columns that you want, [TABLE_NAME] is the table, COLx is the column with which you want to make a where condition and ORDER BY NEWID(), [COL1,COL2 ... COLn] is the key here. NEWID() is the function that does the trick, while [COL1,COL2 ... COLn] are the columns that you want the data to be ordered by.)

There. That’s it. You don’t have to write complex code or spent restless nights. One thing of importance here is that each DB Server has a different method to do the same job. So be careful while using this method. This article assumes that you are a Microsoft SQL Server (7 or above)  user.

At this site, you can find ways to do the above job on different database servers. Check it out. Post your comments to give me feedback about this article to help me improve the way I explain the things. :)

How to Generate Random Records from any table in a database?, 5.0 out of 5 based on 1 rating

If you liked this article, Why not buy me a coffee? via: Donate With Paypal



Leave a Reply


< br />

Sponsored