In my case I am using an embedded H2 database but my problem is in fact general SQL one.
Consider this table in which one record may or may not reference another and in which the same record will never be referenced from more than one place.
CREATE TABLE test (id NUMBER, data VARCHAR, reference NUMBER) ;
INSERT INTO test (id, data)
SELECT x, 'P'||x FROM system_range(0, 9);
UPDATE test SET reference = 2 where id = 4;
UPDATE test SET reference = 4 where id = 6;
UPDATE test SET reference = 1 where id = 7;
UPDATE test SET reference = 8 where id = 9;
SELECT * FROM test ORDER BY id;
ID DATA REFERENCE
----------------------------------
0 P0 null
1 P1 null
2 P2 null
3 P3 null
4 P4 2
5 P5 null
6 P6 4
7 P7 1
8 P8 null
9 P9 8
Now I would like have an SQL that will select test records in a random order with the only one restriction a referenced record will never be selected before the one referring to it.
One thing that will work would be SELECT * FROM test ORDER BY reference, RAND()
but to me this does not seem to be random enough as it will always select all non-referenced records first which reduces the level of randomness.
Say a good and valid result set cold be the one below.
ID DATA REFERENCE
----------------------------------
8 P8 null
2 P2 null
1 P1 null
4 P4 2
3 P3 null
9 P9 8
5 P5 null
6 P6 4
0 P0 null
7 P7 1
I would prefer a pure SQL solution but giving H2 is easy to extend I would not run out creating a custom function by exposing my own Java method.
UPDATE This is not a duplicate of How to request a random row in SQL because:
- In addition to the randomness request I have the reference restriction. In fact the level of complexity of my problem comes from this reference restriction and not from the random.
- I need to select all table records not only one