Is there a way to fill the table with a row number so that count will restart as new group (identified by a separate column) starts? As a result, "row number" column will restart the count when the new attribute value for a group is found, and will produce row number (1,2,3 etc.) record within this group.

This post on stack overflow seems to answer my question, but SQL in QGIS does not allow such statements (DENSE_RANK) (or it does but I don't know how?).

  • Could you mention the QGIS version you used so that it helps others facing similar problems. – mapperx Oct 13 '18 at 5:22

Do you need to use a field calculator? If not, the "Add autoincremental field" algorithm from the processing toolbox does what you want including the grouping.



  • That's exactly what I needed! – Ruslan Jun 13 '18 at 21:34
  • I had a similar problem on QGIS version 2.18.16. I needed to auto increment value using Group value as a criteria. I was able to do it using QGIS3.0.3 On the older version QGIS 2.18.16 the group value option is not present. – mapperx Oct 13 '18 at 5:21

If you know the row number of the beginning of each group, you can create a group_row_number field in the Field Calculator with a simple case when statement.

In my example, I have groups A, B, C and D. Group A is rows 1-4. Group B is rows 5-8. Group C is rows 9-12. Group D is rows 13-17.

Field Calculator expression: enter image description here


enter image description here

The generalized formula is:

  when "groupfieldname" = 'first group name' then @row_number
  when "groupfieldname" = 'second group name' then @row_number - [final_row_number_of_first_group]
  when "groupfieldname" = 'third group name' then @row_number - [final_row_number_of_second_group]
  • Thanks, that works, although I was expecting that there is a cleaner solution. – Ruslan Jun 13 '18 at 20:00

Credits to @Gabriel De Luca from his answer https://gis.stackexchange.com/a/364575/99589

In the Field Calculator use the following expression array_find(array_agg($id,"group"),$id)+1, where "group" is an attribute that will restart the count when a new group appears.



You can also do this with QGIS 3 field calculator more easy:


Replace "GROUPFIELDNAME" with the name of your field you want to group by.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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