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?
Asked
Active
Viewed 675 times
1
1 Answers
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.
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.
Val P
- 3,858
- 1
- 8
- 33

if (maximum("id") is NULL, 1 , maximum("id") + 1)Check this post : https://gis.stackexchange.com/questions/132346/is-there-a-way-of-auto-increment-for-the-id-column-in-qgis. In particular the second answer. – Val P Apr 27 '20 at 20:09NULLusing@row_number, because the system can not calculate the row before that the new feature is created. – Val P Apr 27 '20 at 21:07