0% found this document useful (0 votes)
51 views

MyTechnoBook - Query To Select A Random Record From A Table in A SQL Server Database

This document contains a code snippet to demonstrate how to select a RANDOM record from a table in a SQL Server Database.

Uploaded by

dattatreysindol
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

MyTechnoBook - Query To Select A Random Record From A Table in A SQL Server Database

This document contains a code snippet to demonstrate how to select a RANDOM record from a table in a SQL Server Database.

Uploaded by

dattatreysindol
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

MyTechnoBook – Datta’s Technical Notes..!! http://mytechnobook.blogspot.

com

How to Select a Random Record from a Table in SQL Server

There is a function in SQL Server RAND() which generates Random Numbers. This
function does not work as expected while selecting a RANDOM row from a table in SQL
Server.

To address this issue, there is a workaround to select a RANDOM row from a table in SQL
Server. Here you go…

Create a Temp Table using the following query:

CREATE TABLE #TempTable(


IntValue INT NOT NULL,
StrValue NVARCHAR(20) NOT NULL
)
GO

Now insert some sample data into the Temp Table using the following query:

INSERT INTO #TempTable (IntValue, StrValue)


SELECT IntValue, StrValue FROM (
SELECT 1 AS IntValue, 'String Value 1' AS StrValue
UNION ALL
SELECT 2 AS IntValue, 'String Value 2' AS StrValue
UNION ALL
SELECT 3 AS IntValue, 'String Value 3' AS StrValue
UNION ALL
SELECT 4 AS IntValue, 'String Value 4' AS StrValue
UNION ALL
SELECT 5 AS IntValue, 'String Value 5' AS StrValue
UNION ALL
SELECT 6 AS IntValue, 'String Value 6' AS StrValue
UNION ALL
SELECT 7 AS IntValue, 'String Value 7' AS StrValue
UNION ALL
SELECT 8 AS IntValue, 'String Value 8' AS StrValue
UNION ALL
SELECT 9 AS IntValue, 'String Value 9' AS StrValue
UNION ALL
SELECT 10 AS IntValue, 'String Value 10' AS StrValue) StaticData
GO

Now run the following queries to see how 2 RANDOM rows a selected from Temp Table
every time you run these queries.

SELECT TOP 2 * FROM #TempTable


ORDER BY NEWID()
GO

SELECT TOP 2 * FROM #TempTable


ORDER BY NEWID()
GO

©MyTechnoBook Author: Dattatrey Sindol (Datta)


MyTechnoBook – Datta’s Technical Notes..!! http://mytechnobook.blogspot.com

Here is the output of the above queries. Run these queries a couple times to see the
difference in the number of selected rows every time the above queries are run.

©MyTechnoBook Author: Dattatrey Sindol (Datta)

You might also like