Problem
In the following query, plr_stations
is called twice:
- once to limit the
WHERE
clause; and - once to count the number of results it returned.
The code resembles:
SELECT
m.*,
s.*,
(
SELECT
count(1)
FROM
climate.plr_stations('48.5146','-123.4447')
) AS count_stations
FROM
climate.station s,
climate.measurement m,
(
SELECT
id
FROM
climate.plr_stations('48.5146','-123.4447')
) stations
WHERE
s.applicable AND
s.id = stations.id AND
m.station_id = s.id AND ...
The results of this query are then aggregated by a date query.
Solutions
Populate a temporary table, or an array variable, with the results from the function call.
Update #1
The function call will randomly select a sample of stations if too many stations are inside the spherical polygon defined by the parameters to the function call.
Update #2
The date query aggregation that starts the full query looks as follows:
SELECT
extract(YEAR FROM m.taken) AS year_taken,
avg(m.amount) AS amount,
count(m.amount) AS count_measurements,
md.count_stations,
min(md.elevation) AS elevation_min,
max(md.elevation) AS elevation_max
FROM
climate.measurement m, (
SELECT
m.*,
s.*, ...
Question
How else can the redundant call be eliminated?
Thank you.