QGIS Automatic ID – Adding Automatic Numbering to the “id” Field in QGIS

attribute-tableautoincrementfields-attributesqgisunique id

I'm working on QGIS 3.22.6 and I would like to find a way for my "id" column to be automatically numbered as geometry is added.

I am currently using maximum("id") + 1 within the 'default value' of the Attributes Form, but this isn't good enough as it requires me to manually number the "id" of the first feature to 1 in order for it to work.

Has anyone got a solution?

Best Answer

The first feature returns a NULL for maximum("id") as there are no id values to calculate a maximum on.

To get around this, use the coalesce() function which returns the first non-null value in a series of parameters — coalesce(expression1, expression2, expression3) is a more concise version of CASE WHEN (expression1) IS NULL THEN (expression2) CASE WHEN (expression2) IS NULL THEN (expression3) ....

For the first feature to be 1, use coalesce(maximum("id"), 0) + 1 as your default value.

Which means that when you digitise your first feature and maximum("id") returns NULL, you go to the next parameter in coalesce(), which is 0. Then add 1 to that.

From your second feature onwards, maximum("id") returns the maximum "id" value (maximum "id" from existing features = 1, 2, 3...)

And then adds 1 to that (result "id" for current feature = maximum "id"+ 1 = 2 (1+1), 3 (2+1), 4 (3+1)...)

See Autogenerate consecutive job numbers per group using QGIS expressions and the comments to this answer to Is there a way of auto_increment for the ID column in QGIS.

Related Question