;

How to Get Random Records from Database Table in SQL Server


Tutorialsrack 24/10/2023 SQL SQL Server

In this article, we will learn about how to get random records from the database table in SQL Server. 

In SQL Server, To retrieve random records from a database table, you can use the NEWID() function to generate a random value and then order the result set by this value. 

Here's an example of how to do this:

Syntax
SELECT TOP (N) * FROM YourTableName ORDER BY NEWID();

Where,

  • N = Replace N with the number of random records you want to retrieve.,                                 
  • YourTableName = Replace YourTableName with the name of the table from which you want to fetch random records.,
  • ORDER BY NEWID() = This is the main part of the query. It orders the result set by a random value generated by the NEWID() function, which generates a unique identifier (GUID) for each row. This effectively shuffles the records in a random order.

Example: Get Random Records from SQL Server

Example: Get Random Records from SQL Server
SELECT TOP 10 * FROM [dbo].[Employee] ORDER BY NEWID();

I hope this article will help you to understand how to get random records from the database table in SQL Server. 

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags