I am using SQL Server 2008.
I have a query that pulls two random BikeIDs out of a table called Bikes. The table looks like this:
BikeID BikeName
1 Bob
2 Cindy
3 Carl
4 Joe
5 Jane
I use the NEWID() function to pull two random BikeIDs out like this:
SELECT TOP 2 BikeID
FROM Bikes
ORDER BY NEWID()
My results look like this:
Row - BikeID
1 5
2 1
Row - BikeID
1 3
2 4
Row - BikeID
1 2
2 5
Row - BikeID
1 3
2 3
My problem is that I am coming up with duplicates, meaning I get the same number returned twice, see the last example resultset. I am NOT SURE whether NEWID() can return the exact same number twice or not. If not, then I must have a glitch elsewhere.
These are not actually the results that I am producing. These kinds of results appear on my web page that calls this query. So, I get duplicates on the web page. I have not reproduced these results using just SQL in the database query writer.
Is this the best or right way to get two random rows from a query? Does NEWID() eliminate the possibility of return duplicates?
You shouldn’t get duplicates because you can’t select the same row twice in such a simple query.
So, the simple answer is you have 2 rows with
BikeID = 3