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:
SELECT TOP (N) * FROM YourTableName ORDER BY NEWID();
NEWID()function, which generates a unique identifier (GUID) for each row. This effectively shuffles the records in a random order.
SELECT TOP 10 * FROM [dbo].[Employee] ORDER BY NEWID();
For large tables, this approach can be slow and inefficient, as it has to generate a new GUID for each row, so it's not suitable for very large datasets.
If you need a more efficient solution for large tables, you might consider alternative methods or sampling techniques.
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!