MariaDB [teeworlds]> EXPLAIN SELECT Name, a.ID, Time, DENSE_RANK() OVER (ORDER BY Time) rank FROM record_teamrace AS a JOIN (SELECT ID FROM record_teamrace WHERE Map="Stronghold" GROUP BY ID ORDER BY Time LIMIT 5) AS b on a.ID=b.ID; +------+-------------+-----------------+------+----------------+---------+---------+-------+------+-----------------------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +------+-------------+-----------------+------+----------------+---------+---------+-------+------+-----------------------------------------------------------+ | 1 | PRIMARY | | ALL | NULL | NULL | NULL | NULL | 5 | Using temporary | | 1 | PRIMARY | a | ref | ID | ID | 18 | b.ID | 1 | Using index | | 2 | DERIVED | record_teamrace | ref | PRIMARY,Map,ID | PRIMARY | 514 | const | 728 | Using where; Using index; Using temporary; Using filesort | +------+-------------+-----------------+------+----------------+---------+---------+-------+------+-----------------------------------------------------------+ 3 rows in set (0.001 sec) MariaDB [teeworlds]> EXPLAIN SELECT Name, Time, Rank, TeamSize FROM ( -> SELECT TeamSize, Rank, ID -> FROM (SELECT RANK() OVER w AS Rank, ID, COUNT(*) AS Teamsize -> FROM record_teamrace -> WHERE Map="Stronghold" -> GROUP BY Id -> WINDOW w AS (ORDER BY Time) -> ) as l1 -> ORDER BY Rank ASC -> LIMIT 5 -> ) as l2 -> INNER JOIN record_teamrace as r ON l2.ID = r.ID -> ORDER BY Rank ASC, r.ID, Name ASC; +------+-------------+-----------------+------+---------------+---------+---------+-------+------+-----------------------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +------+-------------+-----------------+------+---------------+---------+---------+-------+------+-----------------------------------------------------------+ | 1 | PRIMARY | | ALL | NULL | NULL | NULL | NULL | 5 | Using temporary; Using filesort | | 1 | PRIMARY | r | ref | ID | ID | 18 | l2.ID | 1 | Using index | | 2 | DERIVED | | ALL | NULL | NULL | NULL | NULL | 728 | Using filesort | | 3 | DERIVED | record_teamrace | ref | PRIMARY,Map | PRIMARY | 514 | const | 728 | Using where; Using index; Using temporary; Using filesort | +------+-------------+-----------------+------+---------------+---------+---------+-------+------+-----------------------------------------------------------+ 4 rows in set (0.001 sec)