Sub topic 3
Filter with the FILTER function
This chapter assumes you can enter formulas, read cell ranges such as A2:D100, and use SORT-style ordering in Google Sheets. FILTER returns a live subset of rows from a range. The source data stays unchanged, and the result updates when the source changes.
Filter rows with FILTER
FILTER takes a range and one or more conditions. Each condition is a column of TRUE or FALSE values with the same number of rows as the range. Rows where every condition is TRUE are returned, so separate conditions combine with AND.
=FILTER(A2:D, A2:A="West", C2:C>1000)To get rows that match either condition (OR), add the condition arrays:
=FILTER(A2:D, (A2:A="West")+(A2:A="East"))Combine FILTER and SORT in one formula
Nest FILTER inside SORT to get a sorted subset in one step. The FILTER result is the input to SORT, and the source range is not touched.
=SORT(FILTER(A2:D, C2:C>=1000), 3, FALSE)Handle no matches and blocked output ranges
When no row meets the conditions, FILTER returns a #N/A error. Wrap the formula in IFERROR to show a message instead:
=IFERROR(SORT(FILTER(A2:D, C2:C>=1000), 3, FALSE), "No matches")FILTER spills its results downward and to the right. If any cell in that output area contains data, the formula shows a #REF! error and displays nothing.
Get the top N rows and unique values
SORTN returns the first n rows after sorting. Its second argument is the number of rows, and its third argument, displaytiesmode, controls ties. A value of 0 returns only n rows, even when later rows tie with the last one.
=SORTN(A2:D, 3, 0, 3, FALSE)UNIQUE returns each distinct value once. Combine it with SORT for an alphabetical list of regions:
=SORT(UNIQUE(A2:A))Filter, group and order with QUERY
QUERY runs a SQL-like statement in one formula. The third argument, 1, tells QUERY that the first row is a header. This formula totals positive amounts by region and orders the totals from highest to lowest:
=QUERY(A1:D, "select A, sum(C) where C > 0 group by A order by sum(C) desc label sum(C) 'Total'", 1)Exercise
Write a formula that returns rows where Region is "West" and Amount is above 1000, sorted by Amount from largest to smallest.
Show answer
=SORT(FILTER(A2:D, A2:A="West", C2:C>1000), 3, FALSE)