I would like to implement paging for a random set
Select * from Animals ORDER BY random(SEED) LIMIT 100 OFFSET 50
I tried to set int to some integer and to some fracture. Doesn't work
How do I seed random in sqlite?
I am tacking a chance here with down votes because similar question already exist - Seeding SQLite RANDOM(). I just didn't get the php solution.
I use this for random from seed in my javascript game i am sure you can quite easily convert it to sql
I would not usually copy an existing answer, but I can see that you have left a comment asking the author of this answer to explain how it works already a few weeks ago and no explanation has been given. I will therefore copy the relevant part and try to explain whats going on. If this explanation is good, do go and vote on the original answer.
The first two rows are just about creating a seed of a sort. The result is a decimal number with lots of decimals like:
Then the sql select uses this number to multiply with the numeric row id of every row in the
SQLite
table. And then the rows are sorted according to the decimal part of the resulting product. Using fewer decimals, the sort order would look something like this:After sorting this would be the result:
In this sample I used only eight rows so the result is not very random looking. With more rows the result will appear more random.
This solution will give you the same order repeatedly as long as:
Short answer:
You can't. SQLite's random() function does not support a seed value.
Not so short answer:
Checking SQLite's func.c shows that random() is defined without any parameters..
..and this randomFunc() just calls sqlite3_randomness() (again without any explicit seed value) to obtain a random value of sizeof(sqlite_int64) bytes.
Internally, the implementation of sqlite3_randomness() (see random.c) will set up the RC4 pseudo-random number generator the first time it is used with random seed values obtained from the OS:
Actually, SQLite's unit test functions themselves just use memcpy() on the global sqlite3Prng struct to save or restore the state of the PRNG during test runs.
So, unless you're willing to do something weird (like create a temporary table of consecutive numbers (1..max(Animals)), shuffle those around and use them to select 'random-seeded' RowIds from your Animals table) I suppose you're out of luck.
I don't know if you're wanting a PHP and iOS solution, but if you are only interested in iOS and dont care much about using the built-in sqlite random() function, you could declare a custom function to use in your queries, one that does take a seed parameter.
.
.