I am trying to measure the distance from the centroid of a building to a river segment using the following function.
CREATE OR REPLACE FUNCTION river_foo_mapper () RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
new.river_distance := subquery.distance
FROM (with center as (
select st_transform(st_centroid(new.geometry),3857) as geom from
foo )
select st_distance(a.geom,st_transform(b.geometry,3857)) as distance
from center as a, rivers as b
order by st_transform(b.geometry,3857) <-> a.geom
limit 1) AS subquery ;
RETURN NEW;
END
$$;
If I run the SQL as a select statement it takes less than 2 seconds but if I run it as a function it takes forever to finish. How best can I optimize this and is my function correct.