Returns random rows from `SELECT` in CockroachDB

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

+3


source to share


2 answers


CockroachDB doesn't offer an efficient way to do this yet! For an inefficient way, you can useSELECT ... FROM ... ORDER BY random() LIMIT 1;



Alternatively, you can handle the shuffling of statement results SELECT

in the application itself. After putting the results into an array (or any other aggregate-like structure), you can also shuffle the order there.

+5


source


For a more efficient way, you can add an integer column randomid

to each row. When pasting, put a random number in this column. Then you can get a random column with:

SELECT ... FROM ... WHERE randomid >= ? ORDER BY randomid LIMIT 1;

Where? is a random number.



Note that you will need additional storage for the random number and you must index the column randomid

.

Also note that you may need to run this query twice (> = and <) to make sure you get the result. Although the probability of deleting the first query will be very low.

0


source







All Articles