In Google Sheets, use the order by clause inside a QUERY formula to sort the rows it returns. Add asc for ascending order or desc for descending order; if you leave the direction out, the sort is ascending.
For example, assuming row 1 contains headers and columns A to C hold product, sales, and region data, this formula returns the rows with the highest sales first:
=QUERY(A1:C100, "select A, B, C order by B desc", 1)
What ORDER BY does
QUERY runs a query against a range and displays the matching results in a separate output area. The order by clause determines the order of those returned rows. It does not rearrange or overwrite the original records, so the source data stays in its existing order while the query result updates when its inputs change.
The clause goes inside the query text, which is the second argument of QUERY. In the example above, order by B desc tells Sheets to sort by the values in column B from largest to smallest. For text, descending order is the reverse of ascending alphabetical order; for dates, it puts later dates before earlier ones.
Sorting is useful when you want a live, filtered or summarized view without manually sorting the underlying table. A sales report, for instance, can show the strongest products first while leaving the source sheet in the order in which sales were entered. Because the result is an array, make sure the cells below and to the right of the formula are clear enough for it to expand.
Basic QUERY ORDER BY syntax
The general pattern is select columns order by column direction. The query language is written as text between quotation marks. A simple query can select all relevant fields and then sort by one of them. With a normal sheet range such as A1:C100, use the sheet column letters in the query.
Assuming headers are in row 1, product names are in A, sales amounts are in B, and regions are in C, use this to show the lowest sales first:
=QUERY(A1:C100, "select A, B, C order by B asc", 1)
The final 1 tells QUERY that the first row of the range contains one header row. If you omit the direction, the formula sorts ascending by default, so order by B has the same direction as order by B asc. Use desc when you need largest-to-smallest numbers, newest-to-oldest dates, or reverse alphabetical text order.
In the query text, keywords such as select and order by are not case-sensitive, but consistent lowercase text is often easier to read. The query string itself must remain inside quotation marks in the formula. Text values used as conditions inside that string generally need single quotation marks, as in where C = 'West'.
Sort by multiple columns
You can add more than one sort key by separating the column and direction pairs with commas. Sheets applies the first key first. It uses the second key only to order rows that have the same value in the first key, and continues in that manner for any additional keys.
Assuming the same product, sales, and region layout in A1:C100, this sorts sales from highest to lowest and puts product names in alphabetical order when sales figures tie:
=QUERY(A1:C100, "select A, B, C order by B desc, A asc", 1)
This tie-breaker is important in practical reports. If you sort only by sales, several products with identical totals may appear in an order that is not useful for comparison. Adding a second key makes those ties predictable. You could instead sort by region first and sales within each region by using order by C asc, B desc.
Each sort key can have its own direction. The direction applies to the column immediately before it, not to every key in the clause. Review the order of the keys carefully: changing the first key changes the main grouping of the result, while later keys only refine ties.
Headers and column references
The header count is a common source of confusion. The third argument of QUERY is the number of header rows at the top of the data range, not the number of columns to return. Use 1 when your range begins with one header row, 0 when it contains only data, or another number when the range has multiple header rows. If left out, Sheets attempts to determine the header count, which may not match your intended layout.
When the data range is an ordinary sheet range, query references such as A, B, and C identify its sheet columns. If your input is a constructed array rather than a straightforward range, use positional references such as Col1, Col2, and Col3. For example, if a query input combines two columns into an array, Col1 means the first column of that constructed input, regardless of its original sheet letter.
Headers in the result may differ from the source headings, especially when you select or calculate columns. You can use the query language’s label clause to give selected columns clearer output labels. Keep the header argument aligned with the actual range: if the range starts at A2 and contains no heading row, the header count should be zero, even if row 1 elsewhere in the sheet has labels.
Combine ordering with filters
In a query, order by commonly follows where. This lets you limit the rows first and then arrange the matching results. For example, assuming A1:C100 has a header row, with product in A, sales in B, and region in C, this returns only West-region records and sorts them by sales from highest to lowest:
=QUERY(A1:C100, "select A, B, C where C = 'West' order by B desc", 1)
The clause order matters. A useful simplified sequence is select, then where if needed, then group by or pivot for summaries, followed by order by, and then limit if you want to cap the result. For example, adding limit 10 after the sort asks for the first ten rows in the sorted result, rather than ten arbitrary source rows.
Ordering also works with grouped queries, but take care to sort by a field that makes sense for the grouped output. When a query summarizes sales by region, the output has one row per region rather than one row per sale. Think through what each result row represents before choosing a sort key; otherwise, a technically valid query may not answer the question you intended.
Dates, text, and mixed data
QUERY sorts according to the values it recognizes in the column. For a reliable chronological sort, dates should be stored as actual date values in Sheets, not as text that merely looks like a date. A date entered as text can sort alphabetically or inconsistently rather than by calendar order. Check the cell format and, if necessary, convert the source values to dates before relying on the ordering.
Numbers should likewise be numeric. Values such as 100 and 20 sort numerically as expected, while text entries such as "100" may not behave like numbers. A column with a mixture of numbers and text can be particularly confusing: QUERY determines a column’s type from its data, and values of a minority type may be treated as null. That can affect both sorting and filters.
If the order looks wrong, inspect the underlying cells rather than only the displayed formatting. Currency symbols or date styles do not necessarily indicate that a value is stored as text, and changing a format alone does not always convert text into a number or date. Clean the data consistently, then confirm the query’s result again. For text sorting, also remember that capitalization, spaces, and spelling differences can make apparently similar values distinct.
Common errors and fixes
- Parse error: Check that the query text is enclosed in quotes, clause names are spelled correctly, and commas separate multiple sort keys. Keep text conditions quoted inside the query string.
- Unexpected header in the results: Check the third QUERY argument. Set it to the number of header rows in the input range, rather than relying on automatic detection.
- Wrong column is sorted: Confirm the range and the reference agree. A query over a regular range uses sheet column letters; a constructed array uses positions such as
Col1. - Rows appear in an odd order: Check whether the column mixes text, numbers, or dates stored as text. Standardize the source values before sorting.
- Array result cannot expand: Clear cells that would overlap the query output. QUERY returns results into neighboring cells and cannot replace existing content there.
Another frequent misconception is that order by sorts the original table. It only sorts the query’s returned view. If you need to permanently rearrange the source records, use the sheet’s sorting tools instead, and consider making a copy first if the original order matters.
QUERY versus other ways to sort
Use QUERY when sorting is part of a larger operation, such as selecting particular columns, filtering rows, grouping records, or limiting the output. Its advantage is that the sorting rules are kept in the formula and update with the input data. Its tradeoff is that the query-language syntax takes some learning, and the result occupies a separate output area.
For a simple formula-based sort without query clauses, Google Sheets also has the SORT function. Assuming row 1 has headers and A2:C100 contains the data, this returns those rows sorted by the second column of that range in descending order:
=SORT(A2:C100, 2, FALSE)
Use FALSE for descending order and TRUE for ascending order. Unlike a QUERY expression, this example does not require writing a query string or specifying a header count because the selected range starts below the headings. For an occasional manual sort, select the data and use Data > Sort range > Advanced range sorting options in Google Sheets in a browser. Ensure the header-row option is set correctly so the heading is not sorted among the records. Manual sorting changes the selected source range, unlike either formula approach.
Excel differs in its available formula tools and syntax; Google Sheets’ QUERY function and its query language are not interchangeable with Excel’s sorting features. If a workbook needs to work in both products, verify the formulas and behavior in each application rather than assuming a QUERY formula will transfer unchanged.
Frequently Asked Questions
How do I sort a QUERY result from largest to smallest?
Put order by followed by the relevant column and desc in the query string, such as order by B desc. This sorts numeric values from largest to smallest.
Is QUERY ORDER BY ascending by default?
Yes. If you write order by B without a direction, Sheets uses ascending order. You can still add asc explicitly to make the intended direction easier to see.
Can I sort by two columns in Google Sheets QUERY?
Yes. Add both sort keys, separated by a comma, for example order by B desc, A asc. The second key breaks ties in the first key.
Why does my QUERY sort dates incorrectly?
The source values may be text rather than actual dates, or the column may contain mixed data types. Convert the source entries consistently to date values and check that the QUERY header count matches the range.
Does ORDER BY change my original data?
No. It sorts the rows returned by the QUERY formula in its output area. To rearrange source records, use a manual range sort or another method that changes the source range.
Related
- Inventory Spreadsheet: Simple Setup and Useful Tips
- Inventory List Spreadsheet Template: Build and Use One
- Google Sheets Inventory Spreadsheet: Setup and Tips
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Add a Shared Mailbox in Outlook App: Setup StepsTo add a shared mailbox in Outlook, first ask your Microsoft 365 or Exchange administrator to grant your…
- Excel Tables: Do They Automatically Add New Rows in Excel?Yes. In Microsoft Excel for Microsoft 365 on Windows, a table will usually expand automatically when you type…
- Excel Freeze Panes: Change Them While Scrolling?No—Excel does not change the Freeze Panes boundary automatically as you scroll. To move it, unfreeze the current…
- Workout Log Template for Google Sheets: Setup & TipsA useful workout log template for Google Sheets can be as simple as a table with the workout…
- How to Not Copy Hidden Rows in Excel Without ErrorsTo avoid copying hidden rows in Excel, select the range you need, choose Home > Find & Select…
- Monthly Budget vs Actual Excel Template: Free SetupYes—you can make a free monthly budget-versus-actual template in Excel with columns for category, budget, actual spending, variance,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.