2

I am working with QGIS 3.10 and would like to create a field in the attribute table which is a unique ID for a feature. I have read that using the @row_number as the expression should provide this capability, but the resulting value is always NULL (both in the Preview and once a feature is created). If I select the field from the Attribute table and apply the @row_number in the expression box and select 'Update All' the table is correctly updated with the row numbers. How can I get the correct row number to show up when the feature is selected and then displayed in the Attribute table?

7
  • Can you explain better your problem? Are you trying to create an ID field that updates automatically when you create a new feature? You can create it with the expression if (maximum("id") is NULL, 1 , maximum("id") + 1) Check this post : gis.stackexchange.com/questions/132346/…. In particular the second answer.
    – Val P
    Commented Apr 27, 2020 at 20:09
  • Yes, you understand the problem. And your suggestion does work but if the feature is updated, the ID will change. This is why I was hoping to use @row_number. Once assigned, I do not want this number to change.
    – mjldbr
    Commented Apr 27, 2020 at 20:41
  • New features have NULL for this field. But the Preview looks correct when I am updating the field in the editor.
    – mjldbr
    Commented Apr 27, 2020 at 21:03
  • With this system, the number shouldn't change. Because you are referring to the attribute already recorded and not to the variable. You can call your field in any way, e.g. "Field_ID" and use this name instead "id" in the expression. Only ], be sure that the option Apply default value on update is not selected.
    – Val P
    Commented Apr 27, 2020 at 21:04
  • New features always will have NULL using @row_number, because the system can not calculate the row before that the new feature is created.
    – Val P
    Commented Apr 27, 2020 at 21:07

1 Answer 1

4

To achieve your request you need to create, on the layer Proprieties-> Attribute Form, a default value by expression.

You can use the expression

IF (maximum("field_id") is NULL, 1 , maximum("field_id") + 1)

where field_id is the name of your autoincremental field.

Also, select the Constrains Not null and Unique.

enter image description here

In this way, for any new feature, you will have a new number autoincrementate by 1. The first part of the expression helps to avoid to have a null number with the first feature created when the field is still empty.

NB. To avoid the number changing, be sure that the option Apply default value on update is not selected.

1

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.