Table.ColumnNames Function in Power Query M

Sumit Bansal
Written by

Sumit Bansal is the founder of TrumpExcel.com and a 13-time Microsoft Excel MVP. He started this site in 2013 to share his passion for Excel through easy tutorials, tips, and training videos, helping you master Excel, boost productivity, and maybe even enjoy spreadsheets!

The Table.ColumnNames function in Power Query gives you the names of all the columns in a table, as a list. It’s the function to reach for when you want a query to keep working after the column names change.

In this article, I’ll show you how to use it with practical examples, from getting the list of names to changing types, renaming, and expanding columns without typing a single column name.

Follow along with the example file

Table.ColumnNames Function Examples.xlsx

Download

Table.ColumnNames Function Syntax

= Table.ColumnNames(table as table) as list
  • table – the table whose column names you want. This is usually the previous step, such as Source. If you give it something that isn’t a table, like a list, you get the error “We cannot convert a value of type List to type Table.”

What it returns – a list of text with every column name in the table, in the same order as the columns.

The Table.ColumnNames function works in Power Query in Excel for Microsoft 365, 2024, 2021, 2019, 2016, and Excel for Mac (Microsoft 365), as well as in Power BI.

When to Use the Table.ColumnNames Function

Use this function when you need to:

  • See all the column names of a table as a list
  • Apply a change to every column without listing each one by name
  • Get the name of a column from its position, like the first or third column
  • Check whether a column exists before a step that needs it
  • Change the type of many columns at once, including new ones that show up later
  • Compare the columns of two tables and find what’s missing
  • Expand all the columns after a merge without typing their names

Example 1: Get All the Column Names of a Table

Let’s start with the basic use, getting the list of column names.

Below is a list of visits at a vet clinic, and I want to get the names of all its columns as a list.

Vet clinic visits table with Pet, Owner, Visit Date, Reason and Fee columns

To follow along, select any cell in the table and go to Data > From Table/Range to open it in the Power Query Editor. If Power Query adds a Changed Type step, use #"Changed Type" in place of Source in the formulas below.

Add a new step (by clicking on the fx icon next to the formula bar) and use this formula:

= Table.ColumnNames(Source)

Result: a list with Pet, Owner, Visit Date, Reason, and Fee

Table.ColumnNames returns a list of the five column names

Here, the function reads the Source table and returns its five column names as a list. The names come back in the same order as the columns, from left to right.

The result is a list, not a table, which is why Power Query shows it under a List header with one name per row.

You’ll rarely stop at this step, though. In the rest of the examples, this list goes inside other functions so they can work with the column names.

Example 2: Replace Nulls in Every Column

Here’s a common cleanup job where you need all the column names.

Below is a bakery’s daily units sold by item, where the blank cells mean nothing was sold that day, and I want to replace every blank (null) with 0 in all the columns.

Bakery units sold by item for Mon to Fri, with blank (null) cells

Load this table into Power Query the same way as in Example 1, then add a new step (by clicking on the fx icon) and use this formula:

= Table.ReplaceValue(Source,null,0,Replacer.ReplaceValue,Table.ColumnNames(Source))

Result: the same table with 0 in every cell that was blank

Every null replaced with 0 across all columns

Here, the Table.ReplaceValue function replaces null with 0, and its last argument is the list of columns to work on. Table.ColumnNames(Source) gives it every column in the table.

If you do this from the ribbon instead (select all the columns, then Transform > Replace Values), Power Query types each column name into the formula, like {"Item","Mon","Tue","Wed","Thu","Fri"}.

So when next week’s file has a Sat column, that step skips it. The formula above picks it up on the next refresh.

Example 3: Get the Name of a Column From Its Position

Sometimes you know where a column is, but not what it’s called.

Below is a list of shipments with their tracking details, and I want the name of the third column.

Shipments table with Tracking No, Carrier, Ship Date, Destination and Status

Load this table into Power Query the same way as in Example 1, then add a new step (by clicking on the fx icon) and use this formula:

= Table.ColumnNames(Source){2}

Result: Ship Date

Table.ColumnNames(Source){2} returns Ship Date

Here, Table.ColumnNames gives the list of all five names, and {2} picks one item from that list. Power Query counts positions from 0, so {0} is the first column and {2} is the third, which is Ship Date.

If you ask for a position the table doesn’t have, like {9} on this five-column table, you get the error “There weren’t enough elements in the enumeration to complete the operation.” Adding a question mark, {9}?, returns null instead of the error.

To get the last column’s name, whatever the number of columns, use List.Last(Table.ColumnNames(Source)).

Example 4: Check If a Column Exists

This next one helps when a query depends on a column that might not be in every file.

Below is an expense claims export where the system writes all the headers in capital letters, and I want to check whether it has a Receipt No column, however it’s capitalized.

Expense claims export with all-caps headers including RECEIPT NO

Load this table into Power Query the same way as in Example 1, then delete the Changed Type step Power Query adds. That step lists every column by name, so on a file without a receipt column it fails before your check can return FALSE.

Then add a new step (by clicking on the fx icon) and use this formula:

= List.Contains(Table.ColumnNames(Source),"Receipt No",Comparer.OrdinalIgnoreCase)

Result: TRUE

Case-insensitive check for Receipt No returns TRUE

Here, Table.ColumnNames gives the list of column names, and the List.Contains function checks whether “Receipt No” is in that list. It returns TRUE because the table has a RECEIPT NO column.

Column names are case-sensitive, so without the third argument, the same formula returns FALSE here. “Receipt No” and “RECEIPT NO” aren’t an exact match, and Comparer.OrdinalIgnoreCase tells List.Contains to ignore the capitalization.

When the capitalization is always the same, you can use Table.HasColumns(Source,"Receipt No") instead, which does the exact-match check in one function. It’s also case-sensitive, so on this export it returns FALSE.

You can use this TRUE or FALSE inside an if statement, so a later step runs only when the column is there.

A TRUE here doesn’t make [Receipt No] work in a later step, though. Column references are still case-sensitive, so that step has to use the real name, [RECEIPT NO].

Example 5: Rename the First Column, Whatever It’s Called

Bank and system exports often change the name of a column from one version to the next.

Below is a bank statement export where the date column is called “Txn Dt” (other exports call it “Posting Date” or “Value Date”), and I want to rename the first column to Date whatever its name is.

Bank statement export whose first column is called Txn Dt

Load this table into Power Query the same way as in Example 1, then delete the Changed Type step Power Query adds.

That step names the Txn Dt column, so on a file that calls it Posting Date, it fails with “The column ‘Txn Dt’ of the table wasn’t found.” before the rename runs.

Then add a new step (by clicking on the fx icon) and use this formula:

= Table.RenameColumns(Source,{{Table.ColumnNames(Source){0},"Date"}})

Result: a table with the Date, Description, Debit, and Credit columns

First column renamed to Date

Here, Table.ColumnNames(Source){0} returns the name of the first column, which is “Txn Dt” in this file. The Table.RenameColumns function then renames it to Date.

If you rename the column from the ribbon, Power Query writes “Txn Dt” into the formula, and the step fails on a file that calls it “Posting Date”. This version reads the current name every time, so it works with all of them.

This relies on the column order, though. Use it only when the date is always the first column in the export.

Follow along with the example file

Table.ColumnNames Function Examples.xlsx

Download

Example 6: Change the Type of All Columns Except the First

This one comes up a lot with monthly data that keeps getting wider.

Below is a table of website visits by page for each month, and I want to make every month column a whole number, including the months that get added later.

Website visits by page for Jan to Apr, columns with no type

When you load this table with Data > From Table/Range, Power Query adds a Changed Type step that lists each column by name, like {"Jan",Int64.Type}. When May gets added to the table, that step doesn’t include it, so May doesn’t get a type.

Load this table into Power Query, select the Changed Type step in the Applied Steps pane, and replace its formula in the formula bar with the one below.

This formula replaces the Changed Type step instead of coming after it, so it reads from Source, not #"Changed Type".

= Table.TransformColumnTypes(Source,List.Transform(List.Skip(Table.ColumnNames(Source)),each {_,Int64.Type}))

Result: the same table with Jan, Feb, Mar, and Apr set to the whole number type

Jan to Apr set to whole number; Page left as any

Here, Table.ColumnNames gives all five names, and List.Skip drops the first one (Page), leaving the four months. Then the List.Transform function turns each name into a pair like {"Jan",Int64.Type}, which is the format Table.TransformColumnTypes needs.

The month headers now show the 123 icon (whole number). When the May column shows up, it’s in the list of names, so it gets the whole number type too, with no change to the formula.

Page now shows the ABC123 (any) icon, because the formula skips it, so it no longer gets the text type the old step gave it. If you need it as text, click the icon on the Page header and choose Text.

Example 7: Keep Only the Columns Whose Names Match

Here’s how to pick columns by a pattern in their names, instead of listing them.

Below is a sales report with each rep’s target and actual sales for every quarter, and I want to keep the Rep column and only the Actual columns.

Sales reps with target and actual sales for Q1 and Q2

Load this table into Power Query the same way as in Example 1, then add a new step (by clicking on the fx icon) and use this formula:

= Table.SelectColumns(Source,{"Rep"} & List.Select(Table.ColumnNames(Source),each Text.EndsWith(_,"Actual")))

Result: a table with the Rep, Q1 Actual, and Q2 Actual columns

Only Rep, Q1 Actual and Q2 Actual kept

Here, the List.Select function goes through all the column names and keeps only those that end with “Actual” (the underscore _ stands for each name as it’s checked). That gives {"Q1 Actual","Q2 Actual"}.

The & joins {"Rep"} to the front of that list, and the Table.SelectColumns function keeps just those three columns. When Q3 Actual is added to the report, it’s selected too.

Text.EndsWith is case-sensitive, so a column called “Q3 actual” wouldn’t be picked up. If your headers aren’t consistent, add Comparer.OrdinalIgnoreCase as its third argument.

Example 8: Find the Columns Missing From a New File

When a file you import every month changes its layout, it helps to know exactly which columns went missing.

Below is this month’s stock list, and I want to find which of last month’s columns aren’t in it.

This month's stock list with Item, SKU, Qty, Unit Cost and Supplier

And here’s last month’s stock list, which has two columns that this month’s list doesn’t.

Last month's stock list with two more columns, Bin and Reorder Level

This query has more than one step, so it goes in the Advanced Editor. Go to Data > Get Data > From Other Sources > Blank Query, then open the Advanced Editor (Home > Advanced Editor) and use this code.

The two tables are named LastMonthStock and ThisMonthStock, and the code reads both by name, so you don’t have to load them into Power Query first.

let
Source = Excel.CurrentWorkbook(){[Name="ThisMonthStock"]}[Content],
LastMonth = Excel.CurrentWorkbook(){[Name="LastMonthStock"]}[Content],
MissingColumns = List.Difference(Table.ColumnNames(LastMonth),Table.ColumnNames(Source))
in
MissingColumns

Result: a list with Bin and Reorder Level

List.Difference returns Bin and Reorder Level

Here, Table.ColumnNames gives the column names of both tables. The List.Difference function then returns the names in the first list (last month) that aren’t in the second (this month), which are Bin and Reorder Level.

To see the new columns instead, swap the two lists. That returns Supplier, the column this month’s file added.

The comparison is case-sensitive, so a column renamed from “Unit Cost” to “Unit cost” would show up as missing too. That’s usually what you want to know before a later step fails on it.

Example 9: Expand All Columns After a Merge

This last one saves a lot of typing when you merge two tables.

Below is a list of project tasks with the Staff ID of the person doing each one, and I want to bring in every column from a separate staff list, without typing the column names.

Project tasks with the Staff ID of the person doing each task

And here’s the staff list, which also has a Staff ID column.

Staff list with Staff ID, Name, Team and Location

The two tables are named ProjectTasks and StaffList. Create a new blank query, open the Advanced Editor, and use this code:

let
Source = Excel.CurrentWorkbook(){[Name="ProjectTasks"]}[Content],
Staff = Excel.CurrentWorkbook(){[Name="StaffList"]}[Content],
Merged = Table.NestedJoin(Source,{"Staff ID"},Staff,{"Staff ID"},"StaffDetails",JoinKind.LeftOuter),
Expanded = Table.ExpandTableColumn(Merged,"StaffDetails",List.RemoveItems(Table.ColumnNames(Staff),{"Staff ID"}))
in
Expanded

Result: a table with the Task, Staff ID, Hours, Name, Team, and Location columns

Tasks with every staff column expanded except Staff ID

Here, the Merged step matches each task to its staff member and puts the matching staff row in a new StaffDetails column. The Expanded step then opens that column into separate columns.

The list of columns to expand comes from Table.ColumnNames(Staff), with Staff ID taken out by the List.RemoveItems function. If you add an Email column to the staff list later, it gets expanded on the next refresh.

Important: Don’t expand all of Table.ColumnNames(Staff) here. The tasks table already has a Staff ID column, so the step fails with “The field ‘Staff ID’ already exists in the record.”

Other Excel Articles You May Also Like:

All Power Query Functions

Sumit Bansal

Sumit Bansal

13x Microsoft Excel MVP

Hey! I'm Sumit Bansal, founder of trumpexcel.com and a Microsoft Excel MVP. I started this site in 2013 because I genuinely love Microsoft Excel (yes, really!) and wanted to share that passion through easy Excel tutorials, tips, and Excel training videos. My goal is straightforward: help you master Excel skills so you can work smarter, boost productivity, and maybe even enjoy spreadsheets along the way!

Get the FREE 51 Excel Tips Ebook

Enter your details and the free PDF is on its way to your inbox.

Hmm, that didn't go through. Please check your email and try again.

No spam. You'll also get my weekly Excel newsletter. Unsubscribe anytime.

Check your inbox!

The ebook is on its way to your email. It usually lands within a couple of minutes.