Lesson 47. Pull Records From A Table At Random

Normally, records come running out of the database in the order they are stored on disk. This order is usually governed by whatever indexes are on the table. However, sometimes you will prefer to get a random sample of records, especially if you have a large table and only want to look at a number of records.

Nerd Note: The records that you are pulling are not truly random as defined by the statistical definition of random. Computers cannot create truly random processes. The records will be pseudo-random and that is good enough.

Run these queries with and without the ORDER BY clause so you can see the difference in the result set.

Examples

Pull All Records At Random

In [ ]:
USE AdventureWorks2016

SELECT *
FROM HumanResources.vEmployee
ORDER BY NEWID()

Pull 20 Records At Random

In [ ]:
USE AdventureWorks2016

SELECT TOP 20 *
FROM HumanResources.vEmployee
ORDER BY NEWID()

Copyright © 2020, Mass Street Analytics, LLC. All Rights Reserved.