29

I make a new column in my attribute table and it has a default value (for example 0). I want to (probably using the field calculator) have the result that row 1 has the value 1, row 2=2 and so on, just like a numbered index.

I'd be thankful for a code example for the field calculator (including the use of $rownum (I think I need this for switching to the line)).

52

Just put $rownum (QGIS 2) or @row_number (QGIS 3+) as the expression. Simple as that. :)

An up-to-date list of all the field calculator functions can be read in the official docs.

  • I followed your approach, however for no apparent reason, the numbers change at one point. It perfectly worked from row 1 to row 129, and after it shifted to 789... is there a way to solve this? – Guillaume Jan 10 at 14:21
  • 1
    Make sure you don't have a display filter active, as there's no reason for it to jump. – lynxlynxlynx Jan 10 at 15:08
7

@ArMoraer has developped an interesting plugin to be able to control the way this automatic numbering is made, it's named "Sort and Number". You can use it to fill a column with unique numbers by taking into account 3 other fields to sort your data like you want before numbering.

See the source topic : Is there a way to assign row number for sorted table by column in QGIS?

7

If you are using QGIS 3 you must used @row_number

enter image description here

1

For me the best and easiest way is just $id, this will return a id number to each row indexing it from 0.

  • It returns each feature ID, but the sequence does not necessarily starts at 0 and may have missing values. It is the case after having deleted an existing feature (i.e. start with a layer having 3 features, delete #2, call to $id will return 0 and 2.) – JGH Aug 22 at 1:55
  • You are right, if there are missing values, then there will be a problem with the real indexing number. However, I guess that call the $id, after deleting rows should corroborate @row_number. If I correctly understood your affirmation. – Vlad Aug 23 at 18:52
  • nope, it will leave holes – JGH Aug 24 at 0:58

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.