Going Stellar

Home/Google Sheets reference

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

ArgumentTypeRequiredWhat it does
datarangeyesThe range to query. Columns are referred to as A, B, C by their position in this range.
querystringyesThe command in the Google Visualization query language, written as text.
headersnumbernoHow many header rows data has. If omitted, Sheets guesses.

Examples

The examples use this table, starting in A1:

RegionProductUnitsRevenue
NorthLamp10250
SouthChair4600
NorthChair6900
EastLamp375
SouthLamp8200
=QUERY(A1:D6, "select A, sum(D) group by A", 1)

Result:

Regionsum Revenue
East75
North1150
South800

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:

ProductUnits
Chair6
Chair4
Lamp10

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:

RegionProductUnitsRevenue
NorthLamp10250
NorthChair6900

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:

RegionOrders
East1
North2
South2

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:

RegionProductUnitsRevenue
NorthChair6900
SouthChair4600

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.

Sources

  1. QUERY (Docs Editors Help)

Markdown version · All functions