How QUERY works
Syntax
=QUERY(data, "select ... where ... group by ... order by ... limit ...", [headers])data- The range to work on, including the header row, like A1:D500.
query- The query text in quotes. Clauses go in this order: select, where, group by, pivot, order by, limit, label.
headers- Optional. How many header rows the data has. Sheets usually guesses right.
Example
Orders are in A1:D500 with Date, Customer, Product and Amount. You want the five customers who spent the most.
=QUERY(A1:D500, "select B, sum(D) group by B order by sum(D) desc limit 5")Returns a small table of 5 customers and their totals, largest first. It spills into the cells below and to the right.
Common mistakes
- Text values in double quotes inside the query. Use single quotes: where B = 'Acme'.
- Clauses in the wrong order, like order by before group by. That gives a parse error.
- Selecting a column that is not grouped or totalled when you use group by. Every selected column must be in group by or inside sum(), count(), avg(), max() or min().
- Using letters with data built from other formulas, like {A1:B10}. Then columns are called Col1, Col2.
Questions people ask
Does QUERY work in Excel?
No, QUERY is Google Sheets only. In Excel, use FILTER, SORT and pivot tables, or Power Query.
How do I use a cell value in a QUERY?
Join it into the text: =QUERY(A1:D500, "select * where B = '"&F1&"'").
Practice it above: type the formula in the formula bar and press Enter to check.