Skip to main content
2 of 5
edited title
MrXsquared
  • 35.6k
  • 22
  • 71
  • 121

Update points geometry in postgis database snapping them to nearest line

I have two tables in the postgis database - points and lines. And I want to update points geometry to snap them to line if they lay within a certain distance.

By now I managed to create a new table with snapped points which has only geometries. This works:

CREATE TABLE new_table AS
SELECT ST_ClosestPoint(lines.geom, points.geom) as snapped_point
FROM lines
INNER JOIN points on ST_Dwithin(lines.geom, points.geom, 5)
ORDER BY points.id;

But what I really need is to update the existing table. So I try:

UPDATE points
SET geom =  
(SELECT ST_ClosestPoint(lines.geom, points.geom) as snapped_point
FROM lines
INNER JOIN points on ST_Dwithin(lines.geom, points.geom, 5)
ORDER BY points.id);

And it never works. Please, help me to put these two pieces together.