I'm trying to do the following in MySQL (specifically MariaDB):
- Out of a database, select n random rows (different rows should be selected every time the query is sent)
- Return those rows in a sorted order (for example by uid or name)
All examples I found for returning a series of random rows (example1, example2, example 3) work by first sorting the table in a random order and then selecting n rows from that table, for example:
SELECT * FROM table ORDER BY RAND() LIMIT 10
The exact keyword used to achieve a random order differs by SQL system used (and there might also be several alternatives for some of them), but all solutions use the ORDER BY keywords.
The obvious problem with that is that it also scrambles the order of the table. However, I need the result in sorted order and I can't order the table in two different ways simultaneously.
I tried to see whether I could chain keywords to achieve the desired result by chaining ORDER BY like this:
-- first order by rand, then select 10, then order the result again
SELECT * FROM table ORDER BY RAND() LIMIT 10 ORDER BY name
However, SQL is a declarative, not an imperative language, so that was never going to work, at least not the way I tried it.
I'm out of ideas, is there a way to do this at all?