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?
1 Answer
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.
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.
-
Does this mean that @row_number doesn't work as described in the training manual: docs.qgis.org/3.34/en/docs/training_manual/forestry/… Commented May 16 at 20:18
if (maximum("id") is NULL, 1 , maximum("id") + 1)
Check this post : gis.stackexchange.com/questions/132346/…. In particular the second answer.NULL
using@row_number
, because the system can not calculate the row before that the new feature is created.