Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlite order by random groups

Tags:

sql

sqlite

I have a table of songs with track and album columns and I want to get them in a random album order. i.e. such that in each album the songs will be sorted but the albums will be in random order.

For example, if the table is:

-----------------
| track | album |
-----------------
| 1     | a     |
| 2     | a     |
| 3     | a     |
| 1     | b     |
| 2     | b     |
| 1     | c     |
| 2     | c     |
-----------------

than a possible output will be

-----------------
| track | album |
-----------------
| 1     | b     |
| 2     | b     |
| 1     | c     |
| 2     | c     |
| 1     | a     |
| 2     | a     |
| 3     | a     |
-----------------

Can it be done with a single sqlite query?

like image 775
Dvir Yitzchaki Avatar asked Apr 01 '26 19:04

Dvir Yitzchaki


1 Answers

First you need to order the albums randomly, and then select the tracks.

with tt as (
  select distinct album from t order by random()
)
select t.track, tt.album 
from tt left join t on t.album = tt.album
order by tt.rowid, t.track
;

See Sqlfiddle

like image 154
MrSimpleMind Avatar answered Apr 03 '26 09:04

MrSimpleMind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!