**Tableau quick tip: Dynamic sorting in Tableau**

Giving the user the ability to sort by whatever measure they want can help them explore the visualisation through lenses they wouldn’t otherwise be able to. Unfortunately I’ve never seen a way to do this, so I decided to play around and figure out a way to sort data based on a parameter. Once you know how to do it, it’s a simple and useful trick. In this blog we’ll use the superstore dataset and use a parameter to sort customers by profit or sales, either ascending or descending.

The first step is to make a crosstab with customers, sum(sales) and sum(profit).

Note that the data source itself is sorted alphabetically. We can use this to our advantage and have that as a sort option. Next we’ll make a parameter that gives the option to select the types of sorts that we want.

Now we need a calculated field, that returns an expression to sort on for each parameter selection. So the calculation can return sales if we want to sort by sales, but what if we want to make it descending? A sort can only be defined in one direction, so instead we will use the fact the the inverse of a number sorts in the opposite direction. If x is large 1/x is very small and if x is small, 1/x is large.

What about the alphabetical sort? the calculation will return all nulls when the parameter is set to alphabetical, so the sort will default to the data source sort, which is already alphabetical. Be careful that your data source is actually sorted alphabetically if you try to do this though.

The final step is to sort customer names by the calculated field.

The user of the viz now has control over how the data is sorted by using the parameter drop down.