Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return random rows from `SELECT` in CockroachDB

Tags:

cockroachdb

How can I select random rows from a SQL table using CockroachDB? For example, if I have a number of questions and I want to generate a different sequence each time a student loads them.

like image 872
Loiselle Avatar asked Jan 05 '23 04:01

Loiselle


2 Answers

CockroachDB doesn't offer an efficient way to do this yet! For a non-efficient way you can use SELECT ... FROM ... ORDER BY random() LIMIT 1;

Alternatively, you can handle shuffling the results of a SELECT statement in your application itself. After putting the results into an array (or any other aggregate-like structure), you can also shuffle the order there.

like image 99
Loiselle Avatar answered Mar 15 '23 16:03

Loiselle


I'm using the following statement to select random number of rows from cockroach db.

SELECT ... FROM ... WHERE round(random()*10) % 10 = 0 LIMIT 10
like image 25
Ahmet Kurukose Avatar answered Mar 15 '23 16:03

Ahmet Kurukose