Sometimes we require to fetch a number of rows from a table but on a random basis. This can be achieved by using newid() function in SQL Server. For the explanation purpose I have taken the following table and columns to run the query.
Table: Mydept
Deptno Dname
10 Microsoft
20 Marketing
30 HR
40 SALES
60 LEGAL
80 MANAGEMENT
50 INFOTECH
70 PROMOTION
90 FACULTY
Query to get 4 random rows from the MyDept Table
Select top(4) deptno, Dname from MyDept order by newId()
The result of the query is:
deptno Dname
80 MANAGEMENT
30 HR
10 Microsoft
60 LEGAL
We can pass on 3, 4, 5 or any number in the top keyword for fetching n number of random rows from the table.