2
create function are_close_to_each_other(g1 geometry, g2 geometry)
returns boolean
language sql immutable as $$
   select ST_DWithin(g1, g2, 100);
$$;

select x.*, y.*
from sometable x, sometable y
where are_close_to_eachother(x.geom, y.geom);

I have an index on sometable (geom). Will this index be used inside function are_close_to_each_other? If not, how to make it use it?

4
  • It's been decades since using a FROM table list was best practice. Nowadays, the JOIN keyword is the only appropriate way to add tables to the base FROM table, which also lobs a softball at the optimizer in generating a query plan.
    – Vince
    Commented May 31, 2021 at 14:18
  • 2
    while st_dwithin is parallel safe, your function is unsafe (by default), so while the spatial index will be used, the seq scan on the 1st table will be much slower when using your function rather than joining on st_dwithin directly
    – JGH
    Commented May 31, 2021 at 14:33
  • Yes, that's also important. Unless you define it as parallel safe it won't be able to run in parallel (using multiple CPUs). Commented May 31, 2021 at 19:02
  • Thanks @JGH for pointing this out. Never knew about this really fundamental and important thing, to mark pretty much all immutable functions as parallel safe. Commented Jun 1, 2021 at 6:34

1 Answer 1

3

It will be used the same way it would be used if the query looked like this:

select x.*, y.*
from sometable x, sometable y
where ST_DWithin(x.geom, y.geom, 100);

Documentation states that ST_DWithin uses available indexes.

You can make sure by running:

explain analyze
select x.*, y.*
from sometable x, sometable y
where are_close_to_each_other(x.geom, y.geom);

If there is "index scan" in the output it means that the indexes were used.

4
  • Thanks for the answer. Am I correct to assume the reason the index is used is because geometries are passed to sql-functions by reference, not by value? Commented Jun 1, 2021 at 6:37
  • Not sure what you mean by that. Index scan has to be performed on an indexed column/expression not on a specific value. Commented Jun 1, 2021 at 12:52
  • I was just thinking, how the function can know about the index. Commented Jun 1, 2021 at 14:16
  • Because ST_DWithin is an index aware function, as mentioned in the documentation. And your function simply calls it with your own argument. postgis.net/docs/ST_DWithin.html This function call includes a bounding box comparison that makes use of any indexes that are available on the geometries. Commented Jun 1, 2021 at 14:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.