Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select random row(s) in SQLite

Tags:

sql

sqlite

In MySQL, you can select X random rows with the following statement:

SELECT * FROM table ORDER BY RAND() LIMIT X 

This does not, however, work in SQLite. Is there an equivalent?

like image 461
Fahad Sadah Avatar asked Nov 06 '10 20:11

Fahad Sadah


People also ask

How do I select random rows in SQLite?

select * from foo where rowid = (abs(random()) % (select (select max(rowid) from foo)+1));

How do you select a random row?

To get a single row randomly, we can use the LIMIT Clause and set to only one row. ORDER BY clause in the query is used to order the row(s) randomly. It is exactly the same as MYSQL. Just replace RAND( ) with RANDOM( ).


2 Answers

For a much better performance use:

SELECT * FROM table WHERE id IN (SELECT id FROM table ORDER BY RANDOM() LIMIT x) 

SQL engines first load projected fields of rows to memory then sort them, here we just do a random sort on id field of each row which is in memory because it's indexed, then separate X of them, and find the whole row using these X ids.

So this consume less RAM and CPU as table grows!

like image 107
Ali Avatar answered Nov 09 '22 11:11

Ali


SELECT * FROM table ORDER BY RANDOM() LIMIT X 
like image 40
Donnie Avatar answered Nov 09 '22 10:11

Donnie