I am using SQL Server 2008.
A while back, I asked the question “should I use RecordID in a junction table”. The tables would look like this:
// Images
ImageID// PK
// Persons
PersonID // pk
// Images_Persons
RecordID // pk
ImageID // fk
PersonID // fk
I was strongly advised NOT to use RecordID because it’s useless in a table where the two IDs create a unique combination, meaning there will be no duplicate records.
Now, I am trying to find a random record in the junction table to create a quiz. I want to pull the first id and see if someone can match the second id. Specifically, I grab a random image and display it with three possible choices of persons.
The following query works, but I’ve quite a bit of negativity that suggests that it’s very slow. My database might have 10,000 records, so I don’t think that matters much. I’ve also read that the values generated aren’t truly random.
SELECT TOP 1 * FROM Images_Persons ORDER BY newid();
Should I add the RecordID column or not? Is there a better way to find a random record in this case?
Previous questions for reference
Consider what you’ve got.
Not truly random? Excluding the ‘truly random is impossible’ bit, you’re probably right – I believe that there are patterns in generated uniqueidentifiers. But you should test this yourself. It’d be simple; just create a table with 1 to 100 in it,
order by newid()a lot of times, and look at the results. If it’s random ‘enough’ for you (which it probably will be, for a quiz) then it’s good enough.Very slow? I wouldn’t worry about that. I’d be very surprised if the
newid()is slower than reading the record from the table. But again, test and benchmark.I’d be happy with the solution you have, pending tests if you’re concerned about it.
I’ve always used
order by newid().