Good day, my question is about optimizing sql query.
The following query is slow:
SELECT id, name,
, (SELECT rank_time FROM stage_rank WHERE stage = stage.id ORDER BY rank_time DESC LIMIT 1)::date AS rank_time
, (SELECT host_c FROM stage_rank WHERE stage = stage.id ORDER BY rank_time DESC LIMIT 1) AS host_c
, (SELECT index_pa FROM stage_rank WHERE stage = stage.id ORDER BY rank_time DESC LIMIT 1) AS index_pa
, (SELECT links_pa FROM stage_rank WHERE stage = stage.id ORDER BY rank_time DESC LIMIT 1) AS links_pa
, (SELECT index_pb FROM stage_rank WHERE stage = stage.id ORDER BY rank_time DESC LIMIT 1) AS index_pb
, (SELECT links_pb FROM stage_rank WHERE stage = stage.id ORDER BY rank_time DESC LIMIT 1) AS links_pb
FROM stage
ORDER BY name;
I think it mostly because of repeated select from stage_rank, is it possible to make this select done once, and get all fields in single hit ?
Also any postgresql specific feaures might be of help here ?
In
PostgreSQL, you can select the whole record as a field and expand it later:or rewrite the query:
or rewrite it the other way: