How to Get Random Records from Table? – Interview Question of the Week #105

Question: How to Get Random Records from Table?

Answer: This question seems to be never get old. I have previously answered this question multiple times on my blog, but I still get this question from many readers who prefer sending email over doing searches on Google.

How to Get Random Records from Table? - Interview Question of the Week #105 randomrecords1-800x272

There are many ways to retrieve random records, here is the one method which I often use it as I can remember the syntax of the same easily.

-- First Execution
SELECT FirstName, LastName
FROM [Person].[Person]
ORDER BY CHECKSUM(NEWID());

You can see in the image when I ran the above script multiple times, every single time it gave us different result. This is because we have used the NEWID() in the order by and it brings back different results every single time.

How to Get Random Records from Table? - Interview Question of the Week #105 randomrecords

Additionally, please note that above query can be quite expensive if you have tables with hundred thousands of the rows.

Here is the additional link for you to refer to the same subject.

Let me know if you are aware of any other method and you believe that is more efficient than the method displayed in this blog post. I will be happy to do another blog post with due credit to you.

Reference: Pinal Dave (https://blog.sqlauthority.com)

SQL Function, SQL Random, SQL Scripts, SQL Server
Previous Post
How to Find Number of Times Function Called in SQL Server? – Interview Question of the Week #104
Next Post
How to Query Multiple SQL Server with a Single Query? – Interview Question of the Week #106

Related Posts

Leave a Reply