Skip to content

Removing columns

M has two main functions for choosing columns: Table.SelectColumns keeps the columns named, and Table.RemoveColumns drops them.

Both take an optional third argument that says what to do when a named column is missing:

  • MissingField.Ignore skips the missing column.
  • MissingField.UseNull keeps the column in the result and fills it with nulls.

Without that argument, a missing column stops the refresh with an error. MissingField.UseNull is usually the more useful option with Table.SelectColumns, because it guarantees that every column the query asks for is present in the output, even when the source no longer has it.

Two further habits make a query less likely to fail on refresh:

  • Name the columns to keep rather than the columns to remove, because a new column in the source then does not need any change to the query.
  • Where columns are reliably in the same place, choose them by position rather than by name, so that a renamed column does not break the step.

The examples below all start from this table:

An Excel table with columns Date, Color, Supplier, City, Category and Revenue, holding five rows of car sales

Table.ColumnNames returns the table’s column names as a list, and the list functions can then pick names from it by position.

To remove the first column:

= Table.RemoveColumns(Source, List.First(Table.ColumnNames(Source)))

The result without the Date column, starting at Color

To remove the last column:

= Table.RemoveColumns(Source, List.Last(Table.ColumnNames(Source)))

The result without the Revenue column, ending at Category

To keep only the second and third columns:

= Table.SelectColumns(Source, List.Range(Table.ColumnNames(Source), 1, 2))

The result with only the Color and Supplier columns

List.Range takes a list, then the position to start from, counting from 0, and then the number of items to return.

To keep two columns that are not next to each other, such as Supplier and Revenue, pick each name by its position in the list, again counting from 0:

= Table.SelectColumns(Source, {Table.ColumnNames(Source){2}, Table.ColumnNames(Source){5}})

The result with only the Supplier and Revenue columns

List.Select filters the list of names with a test, so columns can be chosen by part of their name. This removes every column whose name contains Supp:

= Table.RemoveColumns(Source, List.Select(Table.ColumnNames(Source), each Text.Contains(_, "Supp")))

The result without the Supplier column

The same result comes from Table.SelectColumns with the test reversed, so that it keeps every column whose name does not contain Supp:

= Table.SelectColumns(Source, List.Select(Table.ColumnNames(Source), each not Text.Contains(_, "Supp")))

The same result without the Supplier column, produced by Table.SelectColumns

The technique on this page follows one in Gil Raviv’s Collect, Combine, and Transform Data Using Power Query in Excel and Power BI (Microsoft Press).