Sub topic 13
Get the top N rows and unique values
Assume you already know cell ranges, simple formulas, and the SORT and FILTER functions. This chapter uses a table with one header row and data in A2:D. The columns are Region, Product, Amount, and Date.
Return the top rows with SORTN
SORTN returns the first N rows after sorting a range. Its basic structure is:
=SORTN(range, n, display_ties_mode, sort_column, is_ascending)The sort_column number is relative to the selected range. In A2:D, column 1 is A, column 2 is B, and column 3 is C.
To return the three rows with the largest amounts:
=SORTN(A2:D, 3, 0, 3, FALSE)The formula sorts by column 3 in descending order and returns three rows. The 0 means that the result contains exactly three rows, even if another row has the same amount as the third row.
Use a different ties mode when ties matter. For example, a mode that includes rows tied with the last selected value can return more than N rows. This is useful for a leaderboard, but it may make a dashboard change size.
| Argument | Meaning |
|---|---|
| `A2:D` | Source data without the header |
| `3` | Number of rows requested |
| `0` | Keep a fixed row count |
| `3` | Sort by Amount |
| `FALSE` | Sort from largest to smallest |
SORTN is useful when you need a compact result such as the five largest orders. It does not change the source table.
List each value once with UNIQUE
UNIQUE removes duplicate rows or values while preserving the first-seen order. To list each region once:
=UNIQUE(A2:A)To list regions alphabetically, wrap it in SORT:
=SORT(UNIQUE(A2:A))This combination is useful for building a clean list for a dropdown or a summary. Empty cells can appear as a blank result. If the source column contains extra spaces, values that look identical may be treated as different values. For example, West and West are separate text values.
Use TRIM when inconsistent spaces are the cause:
=SORT(UNIQUE(ARRAYFORMULA(TRIM(A2:A))))ARRAYFORMULA applies TRIM to the entire range instead of one cell at a time.
Choose between top-N and unique values
Use SORTN when you need selected rows, such as the largest orders. Use UNIQUE when you need a distinct list, such as all regions. Both formulas produce live results. When source data changes, the result updates automatically.
Place the formula where enough empty cells are available for its output. A formula that returns several rows is a spill result. Text or formulas in the output area can block it.
> callout tip > Use a separate results area for dynamic formulas. Do not place notes, totals, or manual entries in cells where the result may expand.
Exercise
Write a formula that returns the five largest positive amounts from A2:D, sorted from largest to smallest.
Show answer
=SORTN(FILTER(A2:D, C2:C>0), 5, 0, 3, FALSE)