In QGIS 3.26 I have polygon layers (districts) and line layers (roads) in my project.

I need to sum the line lengths inside the polygons and write them in an attribute table of this polygon. The goal is to see the road length per district.

My approach was to first calculate the length of the roads and write them in an attribute (field name: "length"). Then use a Virtual field in the polygon layer using this query to sum the values:

        filter:=intersects(geometry(@parent), $geometry)

However, I always get NULL as a result.

I also tried it with 'count' instead of 'sum' which worked fine.

  • Firstly in your expression you should be referring to the length column as "length" (double quotes, which refers to the field) rather than 'length' (single quotes, which refers to a static text value of 'length' as in the actual word). Secondly, is your length field a text field type? In which case you will need to use expression:=to_real("length") as the sum aggregate will not work on a text field datatype even if all the values represent numbers.
    – she_weeds
    Oct 25, 2022 at 22:22
  • You are right. That solves my problem. Thank you
    – MarinT
    Oct 28, 2022 at 11:27

1 Answer 1


Just something to consider, you might get double counting with this approach as a road may cross multiple district boundaries.

I would consider using the Union tool to "clip" and attach the district ID to the road network, followed by a table summary.

  • I think you mean interesection, not union
    – Llaves
    Oct 25, 2022 at 20:05

Your Answer

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

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