1

I'm using a Query in Google Sheets to pull data from another sheet. That query looks something like this:

=QUERY('Raw Data'!A2:AB,"SELECT E, A, C, D, Y, R, S WHERE S = 'New York'",1 )

What I'd like to do, though, is build a custom sort order within the function so that the Query automatically sorts by rows that have "string1" in column E, followed by those that have "string2" in column E, etc etc. The desired order is not alphabetical so I can't use a clause to sort in ascending or descending order.

I'd also prefer to do this without having to create another sheet where I rank my sort order in a table.

1 Answer 1

3

You can add a sorting column without having it appear on the sheet, within the query command. Example:

=query({A2:AB, arrayformula(hlookup(E2:E, {"str1","str2","str3",""; 1,2,3,4}, 2, false))}, "select Col3, Col1, Col2 where Col2 = 'New York' order by Col4")

Explanation

arrayformula(hlookup(E2:E, {"str1","str2","str3",""; 1,2,3,4}, 2, false))

creates a column with the order you want. This column gets appended to the queried array using array notation:

{A2:AB, arrayformula(...)}

This new array can now be queried. However, since it's a new array and not something placed in the sheet, one cannot use letters A,B,C... to refer to columns. Instead, one has to write Col1, Col2, etc:

"select Col3, Col1, Col2 where Col2 = 'New York' order by Col4"

Error handling

What if some values in the table are not listed in your order, e.g., null values? Add iferror clause to sort them to the bottom:

arrayformula(iferror(hlookup(E2:E, {"str1","str2","str3",""; 1,2,3,4}, 2, false), 1000)

This gives the sorting order 1000 to the values not listed.


Helper column alternative

If having to switch to Col1 notation is too much of a price to pay, add the helper column

=arrayformula(hlookup(E2:E, {"str1","str2","str3",""; 1,2,3,4}, 2, false))

to the sheet; it would be column AC for you. It can be made hidden so it doesn't get in the way. Then query normally and sort by AC.


Lazy alternative

If there are not too many options, you can just repeat the command and join the results using array notation:

= {query(..., "... E='string1'"); query(..., "... E='string2'"); ...}

Like this:

={ QUERY('Raw Data'!A2:AB,"SELECT E, A, C, D, Y, R, S WHERE S = 'New York' AND E = 'string1'"); QUERY('Raw Data'!A2:AB,"SELECT E, A, C, D, Y, R, S WHERE S = 'New York' AND E = 'string2'") }

You'll need to avoid header rows when doing this, because they would be repeated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.