Apr 13, 2017

SQLite: showing a random record from a table

Random record

If many occasion developer want to get a random record(s) from a table, because they are programming a quizz, or a game - it turns out there is no native instructions for that in SQLite
but you can use this workaround:

SELECT
*, random() as R
FROM Table
ORDER BY R
LIMIT 1 ;

Why it works

It insert a random number (R) for each record and then using the order by there is going to be a selection of the smaller number (R)  - you can even change the LIMIT to get more than one record - let say 3

SELECT *, random() as R FROM Table ORDER BY R LIMIT 3 ;

No comments:

LinkWithin

Related Posts Plugin for WordPress, Blogger...