I am using Entity Query to select nodes of two different types. The fetching seems to be working, but I want to sort the returned values. Both the content types have different date fields. I know I could do this with

$query->addExpression('COALESCE( field_date_1, field_date_2)', 'Date'); 
$query->sort('Date', 'DESC');

but addExpression() isn't an existing method, and the code throws this exception.

Error: Call to undefined method Drupal\Core\Entity\Query\Sql\Query::addExpression()

How can I sort on two or more date fields?

1 Answer 1


Entity queries don't support expressions. To get it around it, add a tag to the query:


Then implement hook_query_alter(), check for the tag, and add the expression there instead:

function mymodule_query_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  if ($query instanceof Drupal\Core\Database\Query\SelectInterface && $query->hasTag('mymodule')) {
  • 2
    Thanks, it worked and hook_query_TAG_alter() too works here. Adding for future references.
    – Akansha
    Commented Sep 22, 2021 at 14:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.