'IF' in 'SELECT' statement - choose output value based on column values 'IF' in 'SELECT' statement - choose output value based on column values database database

'IF' in 'SELECT' statement - choose output value based on column values


SELECT id,        IF(type = 'P', amount, amount * -1) as amountFROM report

See http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html.

Additionally, you could handle when the condition is null. In the case of a null amount:

SELECT id,        IF(type = 'P', IFNULL(amount,0), IFNULL(amount,0) * -1) as amountFROM report

The part IFNULL(amount,0) means when amount is not null return amount else return 0.


Use a case statement:

select id,    case report.type        when 'P' then amount        when 'N' then -amount    end as amountfrom    `report`


SELECT CompanyName,     CASE WHEN Country IN ('USA', 'Canada') THEN 'North America'         WHEN Country = 'Brazil' THEN 'South America'         ELSE 'Europe' END AS ContinentFROM SuppliersORDER BY CompanyName;