I have to implement the following SQL query in Drupal.

select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;

In my case, it may be something like this.

query->fields('n', array('nid', 'type',1 as 'sort_order'));

Can anyone help?


1 Answer 1


You can use addExpression method, which is unfortunately not chainable. The snippet that would make it work is the following.

$query = db_select('Table1', 't1')
  ->fields('t1', array('col1', 'col2');
  ->condition('col1', 0,'=')
$expression= $query->addExpression('ABC', 'col3');

For more information on expressions, here is the official documentation: https://www.drupal.org/docs/7/api/database-api/dynamic-queries/expressions

  • Hi, did you test if it is working for you ? Commented Apr 6, 2017 at 10:16
  • Great @bincy. I was just about to test it, because I hand-wrote it , without testing. Basically for future reference, you can use addExpression to do all of those non-standard selections. Commented Apr 6, 2017 at 10:19
  • Got it! That was really a new information for me.Thanks :)
    – bincy
    Commented Apr 6, 2017 at 10:21
  • Super, I've updated the asnwer with some links, you might want to take a look for future use cases :). Have a nice day Commented Apr 6, 2017 at 10:23

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.