0

As I know it, this is how you select randomly ordered rows in MySQL:

SELECT * FROM test ORDER BY RAND() ASC;

Now this will return me a randomly ordered set of rows.

But what if I wanted to grab the same random set twice? I can't use RAND() again, as that changes every time.

I tried typing in the actual decimal number that RAND() produces, but that didn't seem to work either.

Any help?

2 Answers 2

2

This is actually a very common problem with a common solution across a lot of languages. Most random number generators allow you to pass a seed value on construction, an RNG with the same seed returns the same pattern of results every time a random number is generated.

Most RNGs use some function of the system time as the default seed (no seed passed) to provide a fresh set of numbers every time.

You can use RAND() with a seed RAND(N), this will return the same set of rows, provided that the underlying table remains the same.. If another row is added, for example, another random number will be generated for that row and it could end up anywhere in the result set.

See RAND() docs.

Sign up to request clarification or add additional context in comments.

1 Comment

You did beat me by seconds :-)
2

You could use the same seed:

SET @seed = some_int_value;    -- I did use the julian day count for a daily changing result.
SELECT * FROM test ORDER BY RAND(@seed) ASC;

See RAND

RAND(), RAND(N)

Returns a random floating-point value v in the range 0 <= v < 1.0. If a constant integer argument N is specified, it is used as the seed value, which produces a repeatable sequence of column values. In the following example, the sequences of values produced by RAND(3) are the same in both places where they occur.

1 Comment

You know you can just whap that integer val straight into the function right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.