48

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.

How do I do this in the Field Calculator (including the use of $rownum which I think I need for switching to the line)?

4 Answers 4

84

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

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

1
  • In QGIS 3.28.9, adding a new field via the Field Calculator adds the column but the numbering looks pretty random. I was hoping to sort an existing "suburb" column alphabetically and then add this field so that suburbs close to A are numbered lower than suburbs close to Z. Is there a way to do this?
    – MSC
    Commented Dec 14, 2023 at 0:07
14

@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?

11

If you are using QGIS 3 you must used @row_number

enter image description here

0
4

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

3
  • 3
    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
    Commented Aug 22, 2019 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
    Commented Aug 23, 2019 at 18:52
  • nope, it will leave holes
    – JGH
    Commented Aug 24, 2019 at 0:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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