SORTBY sorts one range by the values in another. That is the difference from SORT, which can only sort by a column inside the array it returns. With SORTBY, the sort key can be a column you don't want to show, a column in a different table, or a calculated array.
The arguments
- array is what you want back.
- by_array1 is what to sort by. It must be the same height as
array, one column wide. - sort_order1 is
1 (ascending, the default) or -1 (descending). - After that, add more pairs: another key, then its order. Each extra key breaks ties in the ones before it.
=SORTBY(A2:B7,C2:C7,-1) returns columns A and B ordered by column C, largest first. Column C itself isn't in the result.
Sorting by a calculation
Because by_array can be any array, you can sort by something that isn't in the sheet. =SORTBY(A2:A7,LEN(A2:A7),-1) lists the tasks from longest name to shortest. =SORTBY(A2:A9,MONTH(B2:B9)) orders rows by calendar month, ignoring the year.
A custom order
Sorting alphabetically puts High before Low before Medium, which is rarely what you want. To sort in your own order, turn each item into its position in a list with MATCH:
=SORTBY(A2:B7,MATCH(B2:B7,{"High","Medium","Low"},0),1,A2:A7,1)
MATCH gives 1 for High, 2 for Medium and 3 for Low, SORTBY sorts by those numbers, and the second key puts the tasks in each priority in alphabetical order. Using more than one key also makes the result easy to predict when many rows share a value.
Shuffling
Sorting by random numbers shuffles a list: =SORTBY(A2:A7,RANDARRAY(ROWS(A2:A7))). The order changes every time the sheet recalculates. See RANDARRAY.
Rules to remember
Each by_array must be the same height as array. If it isn't, SORTBY returns #VALUE!. All the by_array arguments must also point the same way: either all columns or all rows. The result is a spill range, so the cells it needs must be empty or you get #SPILL!. Empty cells and header rows are treated like any other values, so leave the header out of both array and by_array.
Use SORT when the sort column is in the result, because it is shorter. Use SORTBY for everything else.