OK, got to my postgres. Here you are: create or replace function explode_array(in_array anyarray) returns setof anyelement as $$ select ($1)[s] from generate_series(1,array_upper($1, 1)) as s; $$ language sql immutable;
SELECT s.* FROM score s WHERE s.id IN ( select -- Get the high scoring score ID for each game: explode_array(ARRAY( -- Get the high score for game g: SELECT s2.id FROM score s2 WHERE s2.game_id = g.id ORDER BY s2.score DESC LIMIT 5 )) FROM game g ); It takes ~64ms for me Best regards, Vitaliy Tymchyshyn