Google Sheets Query – Select Large Range of Columns Without Manual Entry

google sheetsgoogle-sheets-query

I have a column with dozens and dozens of columns in it that I'm querying data from. I'm using something similar to below to do this, but I'm wondering if there is an easier way? For instance, something like "Select B:Z where K = X" or "Select B through Z where K = X" or "Select * excluding S where K = X"?

=QUERY(data!B1:J30000, "Select B, C, D, E, F,.......

Is it possible to select columns based on a 'range' instead of manually entering each column?

Best Answer

You can generate a comma-separated string of column names with a formula such as

=arrayformula(join(",", substitute(address(1, column(C:F), 4), "1", "")))

(here C:F is the example of a range of columns). The above formula returns the string C,D,E,F which is suitable for use in a query. Optionally, the arrayformula part can go outside. Example:

=arrayformula(query(A1:F, "select " & join(",", substitute(address(1, column(C:F), 4), "1", "")) & " where A <> ''"))

For a short range like C:F this obviously isn't worth the effort, but if you have something like M:AT, then it's probably going to save time.

Explanation

  • column returns a column number
  • address returns A1 notation of the cell at the top of that column (option 4 means no $ will be used)
  • substitute removes row number 1
  • join joins by commas