ST_LineMerge
What is ST_LineMerge?
ST_LineMerge is a PostGIS function that takes a MultiLineString and merges connected segments into the longest possible LineStrings by joining them at shared endpoints. Lines that do not touch any other line pass through unchanged; Y-junctions and loops are preserved as separate pieces.
1ST_LineMerge(geometry amultilinestring) → geometry
2ST_LineMerge(geometry amultilinestring, boolean directed) → geometryIf directed = true (PostGIS 3.3+), the merge respects the direction of each line and only stitches end-to-start connections.
When would you use ST_LineMerge?
Use ST_LineMerge when you have a fragmented set of lines — a road centreline split into many short segments, a river dataset broken at confluences — and want the longest continuous strings for routing, labelling, or measurement. It is the standard cleanup step after ST_Split or ST_Intersection produces many pieces.
1SELECT highway_name, ST_LineMerge(ST_Collect(geom)) AS merged_line
2FROM road_segments
3GROUP BY highway_name;FAQs
Why do I still have a MultiLineString after merging?
ST_LineMerge only joins lines at simple endpoint connections. If three or more lines meet at a junction, the merger can't decide which pair to stitch, so the branches remain separate. Loops (a line whose endpoints are the same point) also stay as-is.
What does the directed parameter do?
With directed = true, merging only happens where line A's endpoint equals line B's start point — direction is preserved. Without it, PostGIS ignores direction and may reverse some segments to stitch them. Use directed merging for directional networks like rivers or one-way streets.
Does ST_LineMerge node the input?
No. It only looks at existing endpoints. If two lines cross without sharing a vertex, they won't be merged. Run ST_Node(ST_Union(geom)) first if you need full topological cleaning before merging.
Can I use ST_LineMerge to close a polygon?
If the input lines form a closed ring (endpoints coincide after merging), you'll get a single closed LineString. To convert that into a polygon, wrap the result with ST_MakePolygon or use ST_BuildArea directly.