QUERY: total sales by region

Lesson 46 of 54

QUERY is a Google Sheets function that filters, groups, sorts and totals a range with a short SQL-like sentence, such as "select A, sum(C) group by A". One formula can replace a pivot table.

In cell E1, write a formula that returns a small report of total Amount for each Region, using QUERY on A1:C9 with "select A, sum(C) group by A".

E1
ABCDEF
1RegionRepAmount
2NorthAna4,200
3SouthLuis3,100
4NorthMarta2,800
5WestJorge5,600
6SouthSofia1,900
7WestPablo2,400
8NorthElena3,500
9SouthDiego2,700

Type in the formula bar above and press Enter to check.

Skip

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.