Tuesday, September 22, 2015

SQL To Select Random Rows From A Table

Today I was asked to randomly pull random 25 records from a database table for a client. It took me a minute or so to remember how to accomplish this.  With that being said, I thought I would type it up for everyone to be able to benefit from it.

I know there are a lot of ways to select random records or rows from a database table, but in this quick article I will show you the Microsoft SQL Server and MySQL syntax required to accomplish the end goal.

Microsoft SQL Server:
SELECT TOP 25 ColumnName FROM TableName
ORDER BY NEWID()

MySQL:
SELECT ColumnName FROM TableName
ORDER BY RAND()
LIMIT 25
If you like this post and want to see more, follow me on my website www.chadcompton.com
Or if you prefer...