Usually I did not copy the existing answer, but I see that you left a comment asking the author of this answer to explain how it has been working several weeks ago, and there were no explanations. Therefore, I will copy the relevant part and try to explain what is happening. If this explanation is good, go and vote for the original answer.
$seed = md5(mt_rand()); $prng = ('0.' . str_replace(array('0', 'a', 'b', 'c', 'd', 'e', 'f'), array('7', '3', '1', '5', '9', '8', '4'), $seed )) * 1; $query = 'SELECT id, name FROM table ORDER BY (substr(id * ' . $prng . ', length(id) + 2)';
The first two lines are only for creating a sort seed. The result is a decimal number with a lot of decimal places, for example:
0.54534238371923827955579364758491
Then sql select uses this number to multiply by the numeric row identifier of each row of the SQLite table. Then the rows are sorted according to the decimal part of the product received. Using fewer decimal places, the sort order will look something like this:
row id row id * seed sort order 1 0.545342384 545342384 2 1.090684767 090684767 3 1.636027151 636027151 4 2.181369535 181369535 5 2.726711919 726711919 6 3.272054302 272054302 7 3.817396686 817396686 8 4.362739070 362739070
After sorting, this will be the result:
row id row id * seed sort order 2 1.090684767 090684767 4 2.181369535 181369535 6 3.272054302 272054302 8 4.362739070 362739070 1 0.545342384 545342384 3 1.636027151 636027151 5 2.726711919 726711919 7 3.817396686 817396686
In this example, I used only eight lines, so the result is not very random. With more lines, the result will seem more random.
This solution will give you the same order if:
- You use the same seed
- There are no new rows in the table, and not a single row has been deleted from the table.