Google-sheets – Why does this Sheets Query Work

formulasgoogle sheetsgoogle-sheets-query

I've been trying to learn the Query function in Sheets, and cannot understand why the Query below works. To me, it looks like there would need to be one more " to close the SELECT clause, but it seems that the last " in the IF statement does the trick.

Can someone explain what I'm missing here?

=query(Listings,"SELECT A, D, G, N, O, P 

WHERE G < "&B3&"

AND N < "&B4&"

AND P < "&B5&"

"&if(B2="All Towns","ORDER BY A"," and D = '"&B2&"' ORDER BY A")

,1)

Best Answer

Maybe there is a missing space before ORDER BY A in the second IF parameter

instead of

if(B2="All Towns","ORDER BY A"," and D = '"&B2&"' ORDER BY A")

it might have to be

if(B2="All Towns"," ORDER BY A"," and D = '"&B2&"' ORDER BY A")
                   ^
                   ^
                   ^

besides that, there is no need of an extra " because the second parameter of QUERY is a text value and the formula included as the second parameter returns a text value.