Table sorting
To produce a result table which can be sorted by any column, use the TableSort extender and then add the table header. Note that an extender does return a new query object that you need to use from that point on.
$query = $query
->extend('TableSort')
->orderByHeader($header);