How to do limit and order by rand() in MS SQL?

If you are a PHP or Java Developer you should be familiar with MySQL database right?

Table name: employee

Id Name Designation Dttime
1 Agurchand Software Engineer 2013-01-07 11:47:10
2 Babu Software Engineer 2013-01-02 01:06:00
3 Abhiesheik Broadcast Engineer 2013-01-10 18:04:02
4 Juki Content Writer 2012-12-27 06:16:32
5 Aparna Social Executive 2013-01-27 03:47:00
6 Arun Sofware Engineer 2012-12-27 08:12:10

If we need to get random 3 records from the above table in MySQL the query will be like this:

SELECT * FROM employee ORDER BY RAND() LIMIT 3

But, in MS SQL we cannot use ‘LIMIT’ and ‘RAND()’ instead we are allowed to use ‘TOP’ and ‘NEWID()’

So, the MS SQL query will be like this:

SELECT TOP 3 * FROM employee ORDER BY NEWID()
I hope this would have helped you today!

Add a Comment

Your email address will not be published. Required fields are marked *