How to Use QUERY Function in Google Sheets: Syntax & Examples
The
QUERY function in Google Sheets lets you run database-like queries on your spreadsheet data using a simple language similar to SQL. You provide a data range and a query string to filter, sort, or aggregate data dynamically. It helps you extract exactly the data you need without complex formulas.Syntax
The QUERY function uses this syntax:
- data: The range of cells you want to query.
- query: A string that describes what data to select, filter, or sort.
- [headers]: Optional number of header rows in your data (default is 1).
The query string uses keywords like SELECT, WHERE, ORDER BY, and LIMIT similar to SQL.
plaintext
=QUERY(data, query, [headers])
Example
This example shows how to select names and scores from a table where scores are above 80, sorted by score descending.
plaintext
=QUERY(A1:B6, "SELECT A, B WHERE B > 80 ORDER BY B DESC", 1)
Output
Name Score
Alice 95
Charlie 90
Eve 85
| Name | Score |
|---|---|
| Alice | 95 |
| Charlie | 90 |
| Eve | 85 |
Common Pitfalls
- Forgetting to wrap the query string in double quotes.
- Using incorrect column letters; columns are referenced as A, B, C, etc., not numbers.
- Not matching the header count with your data, causing wrong results.
- Using single quotes inside the query string incorrectly; use double quotes outside and single quotes inside for text values.
plaintext
=QUERY(A1:B6, "SELECT A, B WHERE B > 80 ORDER BY B DESC", 1) WRONG: =QUERY(A1:B6, SELECT A, B WHERE B > 80 ORDER BY B DESC, 1) RIGHT: =QUERY(A1:B6, "SELECT A, B WHERE B > 80 ORDER BY B DESC", 1)
Quick Reference
| Keyword | Description | Example |
|---|---|---|
| SELECT | Choose columns to show | SELECT A, B |
| WHERE | Filter rows by condition | WHERE B > 80 |
| ORDER BY | Sort results | ORDER BY B DESC |
| LIMIT | Limit number of rows | LIMIT 5 |
| LABEL | Rename column headers | LABEL A 'Name' |
Key Takeaways
Use QUERY to filter and sort data with SQL-like commands inside Google Sheets.
Always wrap your query string in double quotes and reference columns by letters.
Specify the correct number of header rows to get accurate results.
Use WHERE to filter, SELECT to choose columns, and ORDER BY to sort data.
Check your query syntax carefully to avoid errors.