I need to merge adjacent lines in QGIS 3.8, but am having trouble coming up with a way to identify and then merge them in a large data set. (3.8 is as far as my Mac can support)

I tried to convert my lines to polygons and use the "Join multiple lines" plugin. With both of these it seems like I'll need to select everything manually (not a feasible option) first or else it gets messy.

Ex. I want to locate lines like on the right here with touching endpoints, and merge them into one like on the left.

enter image description here


1 Answer 1


One solution would be to union and merge touching lines in a self join SQL, then run a multipart to singlepart geometry with the QGIS geometry tools.

Make a virtual layer - where mylines is your layername - like

select st_linemerge(st_union(m1.geometry)) as geometry
from mylines m1
inner join mylines m2 on st_touches(m1.geometry, m2.geometry)

Then on the virtual layer run Vector > Geometry tools > Multipart to Singleparts

Anyone knows how to include the Multipart to Singleparts in SQL - I am happy to hear ..

  • You can use recursive functions to try and emulate ST_Dump() (the equivalent function in PostGIS). See examples in these answers: gis.stackexchange.com/a/341570/98784 and Chainage points using virtual layer
    – she_weeds
    Apr 14, 2020 at 2:25
  • Here is an example query: WITH RECURSIVE rng(x) AS( SELECT 1 UNION ALL SELECT (x+1) FROM rng LIMIT ( SELECT cast(st_numgeometries(geometry) AS int) FROM line_collected)), line_collected AS (SELECT st_linemerge(st_union(m1.geometry)) as geometry, m1.id FROM mylines m1 INNER JOIN mylines m2 ON st_touches(m1.geometry, m2.geometry)) SELECT geometry_n(lc.geometry, rng.x) AS geometry, rng.x AS part_num FROM rng, line_collected lc;
    – she_weeds
    Apr 14, 2020 at 2:28

Your Answer

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

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