Google Sheets function · Google-only
QUERY in Google Sheets: syntax and examples
QUERY filters, groups and sorts a range with a short SQL-like command written as text. One formula can replace several FILTER, SORT and SUMIF steps. Columns are named by letter, and the command is a string, so quoting matters.
Syntax
QUERY(data, query, [headers])
Arguments
| Argument | Type | Required | What it does |
|---|---|---|---|
data | range | yes | The range to query. Columns are referred to as A, B, C by their position in this range. |
query | string | yes | The command in the Google Visualization query language, written as text. |
headers | number | no | How many header rows data has. If omitted, Sheets guesses. |
Examples
The examples use this table, starting in A1:
| Region | Product | Units | Revenue |
| North | Lamp | 10 | 250 |
| South | Chair | 4 | 600 |
| North | Chair | 6 | 900 |
| East | Lamp | 3 | 75 |
| South | Lamp | 8 | 200 |
=QUERY(A1:D6, "select A, sum(D) group by A", 1)Result:
| Region | sum Revenue |
| East | 75 |
| North | 1150 |
| South | 800 |
Revenue per region. The header of the sum column is added automatically.
Run in a Google Sheet (English US locale) on .
=QUERY(A1:D6, "select B, C where D > 200 order by D desc", 1)Result:
| Product | Units |
| Chair | 6 |
| Chair | 4 |
| Lamp | 10 |
Product and units for rows above 200 revenue, biggest first.
Run in a Google Sheet (English US locale) on .
=QUERY(A1:D6, "select * where A = 'North'", 1)Result:
| Region | Product | Units | Revenue |
| North | Lamp | 10 | 250 |
| North | Chair | 6 | 900 |
All columns for one region. Text in where sits in single quotes.
Run in a Google Sheet (English US locale) on .
=QUERY(A1:D6, "select A, count(B) group by A label count(B) 'Orders'", 1)Result:
| Region | Orders |
| East | 1 |
| North | 2 |
| South | 2 |
Row count per region, with the header renamed by label.
Run in a Google Sheet (English US locale) on .
=QUERY(A1:D6, "select * order by D desc limit 2", 1)Result:
| Region | Product | Units | Revenue |
| North | Chair | 6 | 900 |
| South | Chair | 4 | 600 |
The two rows with the highest revenue.
Run in a Google Sheet (English US locale) on .
Common errors
- Columns are referenced by letter. "select Product" returns #VALUE!, while "select B" works.
- Text values in where need single quotes inside the string. "where A = North" returns #VALUE!, "where A = 'North'" works.
- An aggregate such as sum(D) next to a plain column needs group by. "select A, sum(D)" alone returns #VALUE!.
- Decimals in the command use a dot, even in a locale that writes commas. "where D > 99,5" returns #VALUE!.
Compared with Excel
Excel has no QUERY. The closest tools are FILTER, SORT and GROUPBY in Excel 365, or Power Query for larger jobs.
Questions and answers
What does the third argument of QUERY do?
It tells how many header rows the range has. Use 1 for one header row. Leave it out and Sheets decides on its own how many header rows there are.