views:

1166

answers:

3

In MySQL I can use the RAND() function, is there any alternative in SQLite 3?

A: 

Solved:

SELECT * FROM table ORDER BY RANDOM() LIMIT 1;
Alix Axel
If you can find the answer within four minutes of asking the question, you probably shoulnd't have asked it at all. Next time: Visit google before stackoverflow.
Emil H
I disagree. We have two bits of info here now, how to select a single record randomly,how to list all the records randomly. I have never needed to do either, but if I do, now I know how. I also know that MySQL does it different to SQLlite. A super technical question would be more impressive, but less useful.
Chris Huang-Leaver
My first thought was that there wasn't any function to order results randomly, or if there was such a feature / function it would be considerable more obscure - that's what happens with SQLite triggers for instance.
Alix Axel
+5  A: 

SELECT * FROM table ORDER BY RANDOM() LIMIT 1;

avnic
+2  A: 

using random():

SELECT foo FROM bar
  WHERE id >= (abs(random()) % (SELECT max(id) FROM bar))
  LIMIT 1;
dfa
+1, This is way faster than the other options provided that id is index.
Emil H
Yes this solution is faster, but assumes id starts at 1 and has no gaps. Otherwise rows that follow gaps are "randomly" chosen more frequently than other rows.
Bill Karwin
@Bill, thanks for pointing out the problem on my answer
dfa
Also the lowest ID will almost never be selected.
Lucky