Sub topic 14
Aggregating filtered data with SUBTOTAL
This chapter assumes you can write SUM, AVERAGE, COUNT, MIN, and MAX over a range. It also assumes you know how to turn on a filter in Google Sheets (Data > Create a filter). By the end you will know why those functions give the "wrong" answer on a filtered table, and how SUBTOTAL fixes it.
The problem: basic functions ignore the filter
A filter hides rows that do not match a condition. It does not delete them. SUM, AVERAGE, COUNT, MIN, and MAX read the cells in their range whether the rows are visible or not. After you filter a table, a total built with SUM still reports the whole table.
Here is a small sales table. The header is in row 3 and the data is in rows 4 to 11.
| Row | A (Region) | B (Product) | C (Sales) |
|---|---|---|---|
| 3 | Region | Product | Sales |
| 4 | North | Apples | 120 |
| 5 | North | Pears | 80 |
| 6 | South | Apples | 200 |
| 7 | South | Pears | 60 |
| 8 | East | Apples | 150 |
| 9 | East | Pears | 90 |
| 10 | West | Apples | 40 |
| 11 | West | Pears | 110 |
The next formula sums the whole table, which comes to 850.
=SUM(C4:C11)Now filter column B so that only "Apples" rows are visible. Four rows remain, and the visible sales add up to 510. The SUM formula still returns 850, because the hidden Pears rows are still in the range. The number no longer matches what you see on screen.
How SUBTOTAL is written
SUBTOTAL takes a function code, then one or more ranges.
=SUBTOTAL(function_code, range1, [range2, ...])The function code is a number that picks the calculation. It is not a formula name. The ranges follow the same rules as for SUM, so you can pass several ranges in one call.
For the sales table, this formula returns 510 while the Apples filter is on and 850 when the filter is cleared.
=SUBTOTAL(9, C4:C11)Rows hidden by a filter are always left out of the calculation. The result updates when you change the filter, so the total follows what is on screen.
The function codes
Each of the five basic functions has a code.
| Code | Calculation | Same as |
|---|---|---|
| 1 | Mean | AVERAGE |
| 2 | Count of numbers | COUNT |
| 3 | Count of non-empty cells | COUNTA |
| 4 | Largest value | MAX |
| 5 | Smallest value | MIN |
| 9 | Total | SUM |
Google Sheets supports a few more codes (6 for PRODUCT, 7 and 8 for standard deviation, 10 and 11 for variance). This tutorial does not cover them.
With the Apples filter on, a block of summary formulas gives these results on the sales table.
=SUBTOTAL(9, C4:C11)
=SUBTOTAL(1, C4:C11)
=SUBTOTAL(2, C4:C11)
=SUBTOTAL(4, C4:C11)
=SUBTOTAL(5, C4:C11)The visible values are 120, 200, 150, and 40. The results are 510 for the total, 127.5 for the mean, 4 for the count, 200 for the largest, and 40 for the smallest.
Because each code matches a basic function, SUBTOTAL treats text, blanks, and zeros the same way as its twin. For example, code 2 counts only numeric cells and skips text, just as COUNT does. Code 3 counts non-empty cells, just as COUNTA does. SUBTOTAL has no code for COUNTBLANK.
Two families of codes: 1 to 11 and 101 to 111
Filtering is not the only way to hide rows. You can also right-click a row and choose Hide row. SUBTOTAL has two sets of codes that differ in how they treat rows hidden by hand.
- Codes 1 to 11 skip rows hidden by a filter but still include rows you hid manually.
- Codes 101 to 111 skip both kinds. Add 100 to a basic code to get its manual-hide version, so 109 is SUM, 101 is AVERAGE, and 102 is COUNT.
Suppose the Apples filter is on, and then you manually hide row 6 (South, 200). These two formulas now disagree.
=SUBTOTAL(9, C4:C11)
=SUBTOTAL(109, C4:C11)The first returns 510, because it ignores the filter only. The second returns 310, because the manually hidden 200 is also excluded.
Choose 101 to 111 when "what I can see" should drive the number in every case. Choose 1 to 11 when only the filter should change the result. Pick one family and use it throughout a sheet, so that readers are not surprised.
Where to put the formula
A SUBTOTAL placed inside the filtered range can disappear, because filtering may hide its own row. It can also create a circular reference if the range includes the cell that holds the formula. Two layouts avoid this.
- Put the summary rows above the header, as in the sales table. The filter then covers only the header and data, and the totals stay visible.
- Put the summary in a separate area, such as a side panel or another sheet.
A range that grows is also worth planning for. If you add rows at the bottom of the table, a fixed range such as C4:C11 will not include them unless you insert the new rows inside the range. A bounded range like C4:C1000 works, as long as the empty cells below the data do not matter. Remember that COUNT and SUM ignore blank cells.
Nested SUBTOTAL calls are skipped
If a range contains cells that are themselves SUBTOTAL results, SUBTOTAL ignores those cells. This is useful in a report with several groups. Each group gets its own subtotal row, and a grand total at the bottom covers the full span without counting the subtotals twice.
=SUBTOTAL(9, C2:C4)
=SUBTOTAL(9, C6:C8)
=SUBTOTAL(9, C2:C9)Imagine the first formula sitting in C5 and the second in C9. The third formula, in C10, spans both groups and both subtotal cells. It adds only the plain values, so nothing is double counted. If you used SUM for the grand total, the subtotal cells would be added in as well, and the answer would be too large.
Take care with this behavior. If you copy a subtotal's value as plain text, or build it with SUM instead, the protection is gone.
SUBTOTAL compared with the conditional functions
SUMIF, COUNTIF, and AVERAGEIF also produce a result for a subset of rows, so it is easy to mix them up with SUBTOTAL. They answer different questions.
| Row | SUBTOTAL | SUMIF, COUNTIF, AVERAGEIF |
|---|---|---|
| What decides the rows | Which rows are currently visible | A condition written in the formula |
| Changes when you filter | Yes | No |
| Can ignore hidden rows | Yes | No |
| Works for MIN and MAX | Yes (codes 4 and 5) | No |
| Result depends on someone's filter settings | Yes | No |
A conditional function gives a stable answer that does not depend on how someone left the filter. A report that always needs "total for Apples" should use SUMIF.
=SUMIF(B4:B11, "Apples", C4:C11)SUBTOTAL suits interactive use, where a person filters the table, looks around, and wants the summary to follow. You can combine them, but the result can surprise you. SUMIF cannot see the filter, so its result stays the same when the filter changes.
Errors and edge cases
- Errors in the range. If a cell inside the visible part of the range holds an error such as
#DIV/0!, SUBTOTAL returns that error. Rows that are hidden by the filter are excluded, so an error in a hidden row does not leak out. Wrap the call in IFERROR if you want a message instead. - No visible numbers. Code 1 returns
#DIV/0!when no visible cell holds a number, exactly as AVERAGE does on an empty range. Use=IFERROR(SUBTOTAL(1, C4:C11), "No data")to handle a filter that matches nothing. - Numbers stored as text. A value such as "120" that is left-aligned and stored as text is ignored by codes 1, 2, 4, 5, and 9, just as it is by the basic functions. Code 3 counts it.
- Rounding. SUBTOTAL can be nested inside ROUND, as in
=ROUND(SUBTOTAL(1, C4:C11), 1). - Filter views. A filter view is a saved filter that only you see. SUBTOTAL responds to filtering you apply in your own view. Check the result in the view you are using before you share a number.
Summary of when to use what
- Use SUM, AVERAGE, COUNT, MIN, and MAX when you want every row in the range, regardless of any filter.
- Use SUBTOTAL with codes 1 to 11 when a filter should shape the result.
- Use SUBTOTAL with codes 101 to 111 when manually hidden rows should also be left out.
- Use SUMIF, COUNTIF, or AVERAGEIF when the condition belongs in the formula and the answer must not depend on the filter.
Exercise
A table in A4:C20 has numbers in column C. A filter is on, and you also hid row 9 by hand. Write one formula that returns the average of the visible numbers in C4:C20, ignoring both the filtered rows and the manually hidden row. Then write a second formula that returns "No data" if the filter leaves no numbers.
Show answer
Use the 101 code, which is AVERAGE with manually hidden rows excluded: =SUBTOTAL(101, C4:C20). For the second formula, wrap it in IFERROR: =IFERROR(SUBTOTAL(101, C4:C20), "No data"). Code 1 would still include the manually hidden row 9, so it is the wrong choice here.
Exercise
In the sales table from this chapter, the Apples filter is on. What do =SUM(C4:C11), =SUBTOTAL(9, C4:C11), and =SUMIF(B4:B11, "Pears", C4:C11) return?
Show answer
SUM returns 850, because it ignores the filter and adds every row. SUBTOTAL returns 510, the sum of the four visible Apples rows (120 + 200 + 150 + 40). SUMIF returns 340, the sum of the Pears rows (80 + 60 + 90 + 110). SUMIF also ignores the filter, so it would still return 340 with the Apples filter on.