Friday, June 26, 2020

SQL SERVER : Get Random Records from database table

In this article I am going to explain how to get random records from SQL SERVER database table.

 

When I am working on multiple choice question application, I have got requirement every user have different questions on every test attempt. If I am going to attempt the ASP.NET test, get ASP.NET unique questions from ASP.NET category.

We can achieve this using NEWID() function in SQL Server. NEWID() function is an RFC4122-compliant function that creates a unique value of type uniqueidentifier.

Syntax

Select * from table_name ORDER BY NEWID()

 

Example :

SELECT top 5 * FROM Orders ORDER BY NEWID() 

how to get random records from SQL SERVER database table


When you run this query, on every request you will get different set of 5 rows.

You can check the NEWID() generated value by adding NEWID() as given below: 

SELECT top 5 NEWID() as uniqueid, * FROM Orders ORDER BY NEWID()

   how to get random records from SQL SERVER database table


No comments:

Post a Comment