Select Random Records By SQL

Sometimes, there is a need of selecting random row or record from the database. For example, I am developing a website for online Test, where I want to generate random questions from the database. I have to select random rows from the database. There are lots of ways to get rid off this problem. Here I am showing a simple way to do this.

If you are using Microsoft SQL Server, then SQL NEWID() function will be helpful for you. It returns a Unique Identifier value to the tested result set.

I am showing it with an example.
I have a table named k3TestQuestions 

Now insert some dummy data in it:
select top 50 random records from the table, I will use the following SQL Query:

SELECT TOP 50 * FROM k3TestQuestions ORDER BY NEWID();

The above query will give a different result every time I execute it.


One thought on “Select Random Records By SQL

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s