How to sort on different columns in the same view?
In Drupal 8, if you want to alter an ORDER BY, in particular to use a formula, you have to add an expression and then order by it:

$query-&gt;addExpression('SUBSTRING(thread, 1, (LENGTH(thread) - 1))', 'order_field');
$query-&gt;orderBy('order_field', 'ASC');


There can be some confusion in Views, because their version of addExpression is Sql::addField. And in fact, Sql::addOrderBy let's you add a field and order by it in one call.

So, your code would look like:

$sql = &lt;&lt;&lt;SQL
CASE
     WHEN node_field_data.last_name IS NULL THEN node_field_data.title
          ELSE node_field_data.last_name
END
SQL;

$query-&gt;addField(NULL, $sql, 'last_name_else_title');
$query-&gt;orderby[] = array(
  'field' =&gt; 'last_name_else_title',
  'direction' =&gt; 'ASC',
);


Or just...

$query-&gt;addOrderBy(NULL, $sql, 'ASC', 'last_name_else_title');


Thanks agileadam for pointing out the failure point (see also).