Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Personally, I don't think that having the RecordID column should be advised AGAINST. Rather I'd advise that often it is UNNECESSARY.</p> <p>There <em>are</em> cases where having a single value to identify a row makes for simpler code. But they're at the cost of additional storage, often additional indexes, etc. The overheads realistically are small, but so are the benefits.</p> <p><br></p> <p>In terms of the selection of random records, the existence of a single unique identifier <em>can</em> make the task easier <strong><em>if</em></strong> the identifiers are both sequential and consecutive.</p> <p>The reason I say this is because your proposed solution requires the assignment of NEWID() to <em>every</em> record, and the sorting of <em>all</em> records to find the first one. As the table size grows this operation grows, and can become relatively expensive. Whether it's expensive enough to be worth optimising depends on whatever else is happening, how often, etc.</p> <p>Where there are sequential consecutive unique identifiers, however, one can then choose a random value between MIN(id) and MAX(id), and then SEEK that value out. The requirement that all value are consecutive, however, is often a constraint too far; you're never allowed to delete a value mid-table, for example...</p> <p>To overcome this, and depending on indexes, you <em>may</em> find the following approach useful.</p> <pre><code>DECLARE @max_id INT SELECT @id = COUNT(*) FROM Images_Persons SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (ORDER BY ImageID, PersonID) AS id FROM Images_Persons ) AS data WHERE Images_Persons.id = CAST(@max_id * RAND() + 1 AS INT) -- Assuming that `ImageID, PersonID` is the clustered index. </code></pre> <p>A down side here is that RAND() is notoriously poor at being truly random. Yet it normally perfectly suitable if executed at a random time relative to any other call to RAND().</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload