Using the field calculator in QGIS

“The field calculator lets you create new columns or update existing columns based on an expression.”

Behind every vector layer in QGIS you will find a data table (attribute table). The data in this table describe the attributes of each feature. Sometimes you would like to update the contents of a column or create a new column with contents that are calculated. QGIS provides a tool for doing this which will explore in this worksheet.

You try:

Goal: To manipulate data in the attribute table using the field calculator

  • Load the Countries layer from the exercise data.
  • Set your project projection to World Mollweide (EPSG:54009)
  • Open the attribute table for the layer
  • Enable editing mode
  • Open the field calculator
  • Create a new calculated text column called 'visited' setting the value to 'no'
  • Use manual selection tools to select all the countries you have visited in the table.
  • Use the field calculator again to 'update existing field' setting the value of the visited column to 'yes' for selected rows only
  • Save your table edits
  • Create a categorized style to symbolize all the countries you have visited in green and all the ones you have not yet visited in red.

Check your results
Does your map look something like the screenshot above?

More about

  • You can also use the field calculator from fields tab of the layer properties dialogue.
  • Some formats (e.g. shapefile) place limits on the number of columns you can have and on the length of the field names you can use - in particular, shapefiles limit you to 10 characters
  • You need to ensure you have the needed permissions to add and remove columns - especially if the data source is a relational database.
  • Think carefully before you update a column - once the data is gone there is no 'undo' option to get it back!

The field calculator uses the QGIS expression system for the formulas used to update fields. Expressions are used in many places in QGIS, so it is worth getting familiar with the system. The expression editor provides a detailed list of available functions, and each function has helped with explanations and examples. The result from your expression should be suitable for the column you are calculating - for example if you have a date column, be sure that your expression calculates a date.

You can also combine columns in your expression for example: "column_a" * "column_b" would calculate the product of columns a and b.

Check your knowledge:

  1. The field calculator only works with relational database layers:
    1. True
    2. False
  2. Indicate which statements are correct:
    1. when calculating fields you can either create a new field or update an existing one
    2. The field calculator will automatically work only on the selected fields
    3. Field calculator expressions must be in SQL

Further reading:

Click here to download the sample data for the lesson.