Calculate min distance between points in PostGIS

It's not a simple problem, it involves some kind of forced iteration over the set of candidate points. This chapter from the workshop shows a similar problem, but not exact (your problem is slightly easier)

http://postgis.net/workshops/postgis-intro/advanced_geometry_construction.html

The nearest neighbor searching chapter from the workshop shows the tools you might use to do an index-assisted approach with some external loop driving the query

http://postgis.net/workshops/postgis-intro/knn.html

If your points have a distinct id and you know a distance tolerance (9999) they will all fall within, a self-join and use of the "DISTINCT ON" filter will get you the answer in one go.

WITH unfiltered AS
(
  SELECT t1.id AS id1, t2.id AS id2, ST_Distance(t1.geom, t2.geom) as dist
  FROM t t1, t t2 WHERE ST_DWithin(t1.geom, t2.geom, 9999) AND t1.id <> t2.id
  ORDER BY t1.id, ST_Distance(t1.geom, t2.geom) ASC
)
SELECT DISTINCT ON (id1) id1, id2, dist FROM unfiltered;

It first gathers the candidates combinations of points, and sorts them by distance. Then the "distinct on" filter strips out just the first member of each candidate group, which conveniently is the closest, thanks to the pre-sorting.


Something like that? Be warned, not tested.

UPDATE my_table t1
SET dist = (SELECT ST_Distance(t1.geom, t2.geom) FROM my_table t2 WHERE t2.gid <> t1.gid ORDER BY ST_Distance(t1.geom, t2.geom) LIMIT 1)