The SortByColumns function in PowerApps is used to sort a table based on one or more columns. It provides more flexibility than the Sort function, especially when you need to sort by multiple columns or dynamically change the sorting based on user input.
PowerApps – SortByColumns() function Syntax
SortByColumns(Table, ColumnName1, SortOrder1 [, ColumnName2, SortOrder2, ...])
- Table: The table to be sorted.
- ColumnName1, ColumnName2, ...: The columns by which to sort the table.
- SortOrder1, SortOrder2, ...: The sort order for each column. This can be either Ascending or Descending.
Notes:
- Empty Tables: Ensure the table you are sorting is not empty to avoid unexpected results. You can use IsEmpty to check:
If(!IsEmpty(Orders), SortByColumns(Orders, "OrderDate", Descending))
- Invalid Column Names: Ensure the column names specified in SortByColumns exist in the table to avoid errors.
· Sorting large tables can be computationally intensive. Consider testing the performance impact in your specific use case, especially if the sorting operation is performed frequently or on large datasets. PowerApps - Basic Example of SortByColumns() function
Suppose you have a table named Employees with columns Name, Department, and Salary. To sort this table by the Name column in ascending order:
SortByColumns(Employees, "Name", Ascending)
PowerApps - Sorting table by Multiple Columns
To sort the Employees table by Department in ascending order and then by Salary in descending order within each department:
SortByColumns(Employees, "Department", Ascending, "Salary", Descending)
PowertApps - Dynamically Sort table or collection based on User Choice
Suppose you have a dropdown control named SortColumnDropdown and you want to sort a table named Products based on the user's selection and a toggle control named SortOrderToggle to choose between ascending and descending order:
SortByColumns(
Products,
SortColumnDropdown.Selected.Value,
If(SortOrderToggle.Value, Ascending, Descending)
)
PowerApps – Apply sorting on a Gallery control
If you have a gallery control named Gallery1 bound to a table Orders, and you want to sort the orders by OrderDate in descending order:
// Set the Items property of the gallery
SortByColumns(Orders, "OrderDate", Descending)