How to subtract two columns with db_select()? I have a db_select query that outputs two columns.  I want to find the difference between these columns, output to another column, and then put a condition on this third column.

Here is a mysql query that I want to convert into db-select:

"SELECT *, `column1value`-`column2value` AS `difference` FROM `mytable` WHERE `difference` &gt; 55"
You're looking for MySQL's HAVING, which permits SELECT level aliases.

So this:

SELECT *, `column1value`-`column2value` AS `difference` 
FROM `mytable` 
WHERE `difference` &gt; 55


Becomes this:

SELECT *, `column1value`-`column2value` AS `difference` 
FROM `mytable` 
HAVING `difference` &gt; 55


Which in Drupal-ese is:

$query = db_select('mytable')
  -&gt;fields('mytable')
  -&gt;having('difference &gt; :floor', array(':floor' =&gt; 55));

$query-&gt;addExpression('column1value - column2value', 'difference');


For a simple calculation like this example performance would be better using the expression directly in a WHERE clause. In the example you've given in your answer, I suspect HAVING would be quicker (although MySQL's pretty smart, it may be able to cache that calculation)