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

Taras
  • 32,823
  • 4
  • 66
  • 137
Shepherdjo
  • 2,276
  • 2
  • 22
  • 27

4 Answers4

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.

Taras
  • 32,823
  • 4
  • 66
  • 137
lynxlynxlynx
  • 4,247
  • 3
  • 29
  • 45
  • 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 Dec 14 '23 at 00: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?

gisnside
  • 7,818
  • 2
  • 29
  • 73
11

If you are using QGIS 3 you must used @row_number

enter image description here

Taras
  • 32,823
  • 4
  • 66
  • 137
Leo Cardona
  • 1,363
  • 10
  • 14
4

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

Vlad
  • 77
  • 2
  • 4
  • 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 Aug 22 '19 at 01: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 '19 at 18:52
  • nope, it will leave holes – JGH Aug 24 '19 at 00:58