In case you have your own slow SQL query, you can optimize it automatically here.
For the query above, the following recommendations will be helpful as part of the SQL tuning process.
You'll find 3 sections below:
WITH artists_ranked AS (SELECT
artists_ranked.artist_id,
rank() OVER (ORDER
BY
score) rnk), not_listened_songs AS (SELECT
*
FROM
songs
WHERE
NOT EXISTS (SELECT
1
FROM
listened
WHERE
listened.song_id = songs.song_id)), shuffled_songs AS (SELECT
*
FROM
artists_ranked
JOIN
not_listened_songs
ON not_listened_songs.artist_id = artists_ranked.artist_id
ORDER BY
random()) SELECT
DISTINCT
ON (artist_id) *
FROM
shuffled_songs LIMIT 1