13 Dec 2022

QGIS3: Virtual Layers & Spatialite/SQLite/SQL Queries - Intersecting Lines With Polygons

SQL and Spatialite make super effective table and geometry operations possible. With the implemantation of Virtual Layers, QGIS has now a built in functionality to run such queries very easily and without the need for preparation of databases. The below SQL snippet, i.e., can be used to intersect features of a line and a polygon layer, and calculate the summed segment lengths for each single polygon. The usecase here was, that I needed to know the cummulated lengths of trail crossing single parcels.

SELECT 
  t.Name AS Trail_Name,
  g.GNR AS Parcel_NR,
  SUM(LENGTH(INTERSECTION(t.geometry, g.geometry))) AS SUM_L_inP,
  COLLECT(INTERSECTION(t.geometry, g.geometry)) as geom
FROM Trails AS t JOIN Parcels AS g ON INTERSECTS(t.geometry, g.geometry)
GROUP BY g.GNR