I have a layer from spatialite. When I add a feature I want to know it's identifier (based on the primary key (integer) which is auto-incremental : for example XXXXXX-72) before the creation on the entity (attributeForm OK + commit) by using pyqgis.

My issue is when i delete one or several features. I can predict the next identifier only if I know how many features I've deleted which will quasi never be the case.

I can only access the number of features or every unique id but that doesn't help much when, for example, the last three features were deleted.

Is it possible to access the sequence of the table that store every unique identifier ?

  • 1
    Have a look at gis.stackexchange.com/q/180267/45346 where access to feature id is discussed
    – Detlev
    Commented Nov 26, 2017 at 7:42
  • That was an interesting read and as I can see you had a similar problem than mine. But I have a question : Is it dependant of the current work session ? I mean if the last actions you've made were to delete 3 features (not necessarily the last three). What will happen with the solution you provide (and were answered with) since it doesn't stores the id somewhere ? Commented Nov 27, 2017 at 9:27

1 Answer 1


I've found a workaround.

I've created a table that mimics the sqlite_sequence table in my db because before the first insert the sequence doesn't exists in this system table and also you can't create triggers on it. My table stores the name of the layers that interests me and the current status of their auto-incremental id sequences. It starts with 0 for each since no features are present in these layers and I added triggers (after insert and after delete) to my layers that update the sequence values with the one in sqlite_sequence. I load it to the qgis ToC as a view so that it's automatically updated and create functions that use the values of this table to anticipate the next PK_UID and create the adequate identifier before the feature is commited to tha database.

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.