Skip to content

Instantly share code, notes, and snippets.

@pramsey
Last active August 29, 2022 18:08
Show Gist options
  • Select an option

  • Save pramsey/87f8d7cb0633282c37e5 to your computer and use it in GitHub Desktop.

Select an option

Save pramsey/87f8d7cb0633282c37e5 to your computer and use it in GitHub Desktop.
Convert a Linestring into a set of two-point segments
CREATE TABLE lines (
gid integer primary key,
geom geometry(Linestring, 4326)
);
INSERT INTO lines VALUES (1, 'SRID=4326;LINESTRING(1 1, 2 2, 3 3, 4 4)');
INSERT INTO lines VALUES (2, 'SRID=4326;LINESTRING(0 1, 0 2, 0 3, 0 4)');
WITH
dumps AS (
SELECT gid, ST_DumpPoints(geom) AS pt FROM lines
),
pts AS (
SELECT gid, (pt).geom, (pt).path[1] AS vert FROM dumps
)
SELECT a.gid, ST_AsText(ST_MakeLine(ARRAY[a.geom, b.geom])) AS geom,
a.vert, b.vert
FROM pts a, pts b
WHERE a.gid = b.gid AND a.vert = b.vert-1 AND b.vert > 1;
-- High performance alternative
WITH segments AS (
SELECT gid, ST_AsText(ST_MakeLine(lag((pt).geom, 1, NULL) OVER (PARTITION BY gid ORDER BY gid, (pt).path), (pt).geom)) AS geom
FROM (SELECT gid, ST_DumpPoints(geom) AS pt FROM lines) as dumps
)
SELECT * FROM segments WHERE geom IS NOT NULL;
@caiohamamura
Copy link
Copy Markdown

What about using DumpPoints result into ST_Split function? See my fork https://gist.github.com/caiohamamura/d53c77887df137159d800701adc7cdf2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment