I have a list of points with field data in the attribute table. I want to have the distance between point id₁ and point id₁-1 (previous point in table).

Can I write this as a formula in the attribute table to get the result directly there for the same layer?

2 Answers 2


To calculate the length to the last point in the attribute table, create a new field with field calculator and this expression:

length (
    make_line (
        geometry (
            get_feature_by_id (

enter image description here


From a SQL perspective, using Geopackages, SQLite, PostGIS, etc.:

For something that simple, you can just self-join on id = id+1. For something a bit more complex, you can use the lag() function. Just bear in mind that not all SQL platforms have the lag() function implemented, but since the field, you're joining on is predictable, that's not an issue for your specific question.

select a.fid,
       st_distance(a.geom,b.geom) as distance, 
       makeline(a.geom,b.geom) as geom
from points a
inner join points b on a.fid = (b.fid + 1)

Where fid is your "id" field and points your GeoPackage layer name. If you haven't yet discovered the awesome power of GeoPackages and QGIS' DB Manager, just export that layer as a GeoPackage and run the query there, by opening the SQL window after connecting to your GeoPackage:

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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