How to Use Column Names using Query function

Using column names with the Query function in Google Sheets is not possible directly since the function doesn't support column names. However, you can use a workaround to achieve a similar effect. The approach is to use the Col1, Col2, etc., notation in the Query function and then create a reference table to substitute the column names back into the output.

Here's how to do it:

  1. Create a reference table in your Google Sheet that contains the column names and their corresponding column numbers. For example:
    A B
    Name Col1
    Age Col2
    Country Col3
  2. Use the INDIRECT function in conjunction with the QUERY function. The INDIRECT function will help us fetch the column numbers based on the column names.

Example:

Example

Assume we have the following data in Sheet1:

A B C
Name Age Country
Alice 25 USA
Bob 30 Canada
Charlie 22 UK

And we created a reference table in Sheet2:

A B
Name Col1
Age Col2
Country Col3

Now, if we want to use the column names 'Name' and 'Country' in our query, we can use the INDIRECT function to fetch their corresponding column numbers and use them in the QUERY function like this:

=QUERY(Sheet1!A1:C4, "SELECT " & INDIRECT("Sheet2!B" & MATCH("Name", Sheet2!A:A, 0)) & ", " & INDIRECT("Sheet2!B" & MATCH("Country", Sheet2!A:A, 0)) & " WHERE " & INDIRECT("Sheet2!B" & MATCH("Age", Sheet2!A:A, 0)) & " > 20")

This will produce the following output:

A B
Name Country
Alice USA
Bob Canada
Charlie UK

The above formula first identifies the column numbers based on the column names using the MATCH and INDIRECT functions and then uses these column numbers in the QUERY function.

Did you find this useful?