1

I want to add a new field to my feature attribute table. In this field, I want to generate a random ID (just a number, like 1, 2, 3, etc.) for every new and existing point I create on the map.

This is particularly important for new points, so I need it to automatically generate a new ID for each new point.

7
  • What software are you using? What's the format of your data (e.g. Shapefile, GeoPackage etc.)? Commented Jul 9 at 12:44
  • QGIS 3.28.10 and the format is Shapefile
    – Agos
    Commented Jul 9 at 13:19
  • So... you use $id?
    – Erik
    Commented Jul 9 at 13:21
  • A sequential value isn't really a "random" ID. Shapefiles have an ID that is allocated sequentially but you can't control it -- if you delete a record, all records after that will be reduced by one with the next save. If you never delete features, then I guess this isn't an issue.
    – Vince
    Commented Jul 9 at 13:32
  • As an expert can understand i'm a new user. I tried with $id. What i need is that when i generate a new point it get assigned automatically an id.
    – Agos
    Commented Jul 9 at 13:43

1 Answer 1

6

First add a numerical field named id or whatever you wish to your layer.

Then open the layer properties and navigate to "Attributes form". Select your id field and scroll down to default. Add array_length(array_agg(@id))+1 as expression. You can also uncheck "editable" to prevent it from beeing edited by user or change the widget type to "hidden" to not even show it when adding features.

enter image description here

Note that @id or $id do not work here because these values will be assigned after a feature is added, and are therefore not available while adding a feature.

Also not that array_length(array_agg(@id))+1 may produce duplicates if you delete features. In that case you may want to use something like array_max(array_agg("id"))+1 instead. Note that here @id has been replaced by the field "id". Note that here you may get gaps in your id sequence if you delete features.

Also consider to use the options "Unique" or "Not null" if you want to show a hint in case the rule is about to be broken.

0

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