The Google Sheets QUERY function lets you pull, filter, sort, and summarize data with a single formula using a SQL-like syntax. The basic form is =QUERY(data, query, [headers]), where the query string is written in Google Visualization API Query Language, not standard SQL. For example, =QUERY(A1:C100, "select A, B where C > 10", 1) returns columns A and B for rows where column C exceeds 10.
What Is the QUERY Function?
QUERY is a built-in Google Sheets function that runs a query against a range of cells. It was introduced in 2010 as part of Google Sheets’ enhanced functions, and it remains one of the most powerful tools for data manipulation without writing scripts. The function takes three arguments:
- data – the range of cells to query, such as
A1:D100or a named range likeSalesData. - query – a text string containing the query in the Google Visualization API Query Language. This string must be enclosed in double quotes, or you can reference a cell containing the query text.
- headers – optional; a number indicating how many top rows are header rows. If omitted, Sheets guesses based on the data. Use
1if the first row contains headers.
The result is a new array that appears in the cell where you enter the formula. The output updates automatically when the source data changes.
Core Query Clauses You Must Know
The query string itself is built from clauses that resemble SQL. The most commonly used clauses are:
- select – chooses which columns to return. You can use column letters (A, B, C) or, if headers are specified, you can use the header names in backticks, e.g.,
select `Name`, `Amount`. - where – filters rows based on conditions. For example,
where B > 100orwhere C = 'Paid'. - order by – sorts the result. Use
order by A ascordesc. - group by – aggregates rows with the same value in a column, often used with aggregate functions like
sum(),avg(),count(). - limit – restricts the number of rows returned, e.g.,
limit 10. - offset – skips a number of rows before returning results, e.g.,
offset 5. - label – renames column headers in the output, e.g.,
label A 'Product', sum(B) 'Total'. - format – changes the display format of values, such as
format B 'yyyy-mm-dd'.
Clauses are written in order: select ... where ... group by ... order by ... limit ... offset ... label ... format .... Not all are required; you can use just select and where.
How to Write a QUERY Formula: Step-by-Step
Let’s walk through a real example. Suppose you have a spreadsheet with sales data: column A has product names, column B has sales amounts, and column C has regions. You want to find total sales per region for amounts above $500.
- Click an empty cell, say E1.
- Type
=QUERY(. - Select the data range, e.g.,
A1:C100(include headers). - Type a comma, then a space, then the query string in double quotes:
"select C, sum(B) where B > 500 group by C label sum(B) 'Total'". - Type a comma, then
1for headers, and close the parenthesis:=QUERY(A1:C100, "select C, sum(B) where B > 500 group by C label sum(B) 'Total'", 1). - Press Enter. The result shows each region and the total sales for that region, with the header ‘Total’.
Note: in the query string, text values must be enclosed in single quotes, like 'Paid'. Column references are letters, not numbers. If your data has a header row, always specify the headers argument to avoid misinterpreting the first row as data.
Common QUERY Errors and How to Fix Them
QUERY is finicky, and errors are common. Here are the most frequent issues and their fixes:
- #VALUE! error – “Unable to parse query string”: This usually means a syntax error in the query. Check for missing commas, unclosed quotes, or incorrect clause order. For example,
select A where B > 10is fine, butselect A where B > 10 order by Ais correct order. If you see “PARSE_ERROR”, double-check your column references and operators. - #REF! error – “Function QUERY parameter 1 cannot be parsed”: This often occurs when the data range is invalid or contains mixed data types. Ensure the range exists and is contiguous.
- #N/A error – “No data”: The query returned zero rows. Verify your conditions; maybe the column letters are wrong or the comparison is incorrect.
- Mixing data types: QUERY treats columns as a single type. If a column has both numbers and text, you may get errors. Use
where A is not nullto filter blanks, and consider usingvalue()ortext()functions to convert types. - Case sensitivity: String comparisons are case-sensitive by default. Use
lower()orupper()to normalize, e.g.,where lower(C) = 'paid'.
Also, remember that QUERY does not support wildcards like * or ? in the same way as Excel; use contains or starts with instead.
QUERY vs. Other Functions: When to Use What
QUERY is powerful, but it’s not always the best choice. Compare it with other functions:
- FILTER: Simpler for basic filtering.
=FILTER(A1:C100, B1:B100 > 100)returns all columns for rows where B > 100. QUERY can do the same but with more verbose syntax. - SUMIFS / COUNTIFS: Use these for simple conditional sums or counts without needing to output a full table. QUERY is overkill for a single aggregate.
- UNIQUE: To get distinct values,
=UNIQUE(A2:A100)is simpler than=QUERY(A2:A100, "select A group by A"). - Pivot Tables: For heavy aggregation and interactive exploration, a pivot table is easier to set up and refresh than writing a complex QUERY with
pivotclause.
Use QUERY when you need to combine filtering, sorting, and aggregation in one formula, or when you want to build a dynamic report that updates automatically. For quick one-off tasks, stick with dedicated functions.
Advanced QUERY Techniques: Pivot, Date, and Text Functions
Beyond the basics, QUERY supports advanced features:
- Pivot: The
pivotclause transforms rows into columns. For example,=QUERY(A1:D100, "select B, sum(C) group by B pivot D", 1)creates a summary table with unique values of D as column headers. - Date handling: To filter by date, use the
datekeyword. For example,where A > date '2023-01-01'. You can also useyear(),month(),day()functions inside the query, e.g.,where year(A) = 2023. - Text functions: QUERY has built-in text functions like
lower(),upper(),trim(),contains,starts with,ends with. For example,where C contains 'North'. - Arithmetic: You can perform calculations in the select clause, e.g.,
select A, B * 1.1 as 'WithTax'. - Aggregate functions: Besides
sum,avg,count, you havemin,max, andcountwithdistinct, likecount(distinct A).
These features make QUERY a mini database engine inside your spreadsheet.
Performance and Best Practices
QUERY can slow down your sheet if used excessively or on huge ranges. Here are tips:
- Limit the data range to the actual used rows, e.g.,
A1:C1000instead ofA:C. - Avoid referencing entire columns unless necessary; use
A1:C100. - Use
limitandwhereto reduce output size. - If you have many QUERY formulas, consider using a single QUERY to output a combined dataset, then reference that with other formulas.
- For large datasets, use
QUERY(IMPORTRANGE(...), ...)carefully, as it can be slow. - Remember that QUERY is case-sensitive for column letters; always use uppercase.
Also, note that QUERY does not support dynamic arrays in the same way as Excel’s FILTER; it returns a static array that expands automatically, but you cannot spill it with # like in Excel.
Frequently Asked Questions
Can I use QUERY with data from another sheet or file?
Yes, you can use IMPORTRANGE as the data argument. For example, =QUERY(IMPORTRANGE("spreadsheet_url", "Sheet1!A1:C100"), "select * where B > 10", 1). You must first grant access to the external sheet. This is useful for combining data from multiple files.
How do I reference a cell value inside the query string?
You can concatenate the cell reference using the ampersand operator. For example, if cell E1 contains the number 100, use =QUERY(A1:C100, "select * where B > "&E1, 1). For text, wrap the cell value in single quotes inside the concatenation: "where C = '"&E2&"'".
Why does my QUERY return a blank row or column?
This often happens when there are null values or empty cells in the data. Use where A is not null to filter out blanks. Also, if you have a header row, ensure the headers argument is set correctly; otherwise, the first row might be treated as data.
Is QUERY case-sensitive?
Yes, by default string comparisons are case-sensitive. To make them case-insensitive, use lower() or upper() on both sides: where lower(C) = 'paid'.
Can I use QUERY to combine multiple sheets?
Yes, you can use {Sheet1!A1:C100; Sheet2!A1:C100} as the data range, but the columns must match. Alternatively, use VSTACK (available in newer versions) to combine, then QUERY on the result. Note that VSTACK requires Google Sheets, not Excel.
What’s the difference between QUERY and SQL?
QUERY uses the Google Visualization API Query Language, which is similar to SQL but has limitations. For example, it does not support JOIN operations, subqueries, or WITH clauses. It also uses column letters instead of column names, and string literals use single quotes. For complex joins, you’d need to use ARRAYFORMULA or Apps Script.
Related
- Data Entry Skills Required? A Practical List
- Google Sheets Query or Statement? Clear Answer
- Google Sheets Query Offset: How to Skip Rows
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Group Rows in Excel Based on Criteria Step by StepTo group rows in Excel by a category or rule, first sort the data so matching rows are…
- Add a Custom Number Format in Excel: Steps & ExamplesTo add a custom number format in Excel for Microsoft 365 on Windows, select the cells, press Ctrl+1,…
- Excel Page Break Based on Cell Value: How to Set ItExcel cannot create a page break directly from a cell value with a worksheet formula or built-in conditional…
- How to Sum a Column in the Google Sheets Mobile AppTo sum a column in Google Sheets on your phone or tablet, tap an empty cell where you…
- Lock a Column in Google Sheets: Freeze or Protect ItTo keep a column visible while you scroll in Google Sheets, freeze it with View > Freeze. To…
- How to Indent Text in an Excel Text Box Step by StepTo indent text in an Excel text box, click inside the paragraph, right-click and choose Paragraph if that…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.