This article is half-done without your Comment! *** Please share your thoughts via Comment ***
In this post, I am sharing a small demonstration to get the random result of your SELECT statement in SQL Server.
We can use NEWID() which creates a unique value type of uniqueidentifier. You just need to ORDER BY your result set using NEWID() and you will get the random result every time.
You should also know about the UUID:
Database Theory: The truth about Universally Unique Identifier – UUID
Create a sample table:
1 2 3 4 5 6 7 |
CREATE TABLE tbl_Students ( Rno INT PRIMARY KEY ,STudName VARCHAR(20) ,ClassName CHAR(1) ) GO |
Insert a few sample records:
1 2 3 4 5 6 |
INSERT INTO tbl_Students VALUES (1,'Anvesh','A'),(2,'Neevan','B'),(3,'Toby','C') ,(5,'Roy','A'),(4,'Jenny','B'),(6,'Kaviy','C') ,(7,'Martin','A'),(8,'Laxmi','B'),(9,'Nion','C') GO |
Use NEWID() in ORDER BY to get random results:
I executed below query three times, below you can find three random results.
1 2 3 4 |
SELECT *FROM tbl_Students ORDER BY NEWID() GO |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#1 Rno STudName ClassName ----------- -------------------- --------- 2 Neevan B 6 Kaviy C 1 Anvesh A 3 Toby C 8 Laxmi B 9 Nion C 4 Jenny B 5 Roy A 7 Martin A #2 Rno STudName ClassName ----------- -------------------- --------- 1 Anvesh A 2 Neevan B 8 Laxmi B 9 Nion C 7 Martin A 4 Jenny B 6 Kaviy C 5 Roy A 3 Toby C #3 Rno STudName ClassName ----------- -------------------- --------- 3 Toby C 1 Anvesh A 6 Kaviy C 8 Laxmi B 5 Roy A 4 Jenny B 2 Neevan B 9 Nion C 7 Martin A |
Leave a Reply