Case statement in MySQL Case statement in MySQL database database

Case statement in MySQL


Yes, something like this:

SELECT    id,    action_heading,    CASE        WHEN action_type = 'Income' THEN action_amount        ELSE NULL    END AS income_amt,    CASE        WHEN action_type = 'Expense' THEN action_amount        ELSE NULL    END AS expense_amtFROM tbl_transaction;

As other answers have pointed out, MySQL also has the IF() function to do this using less verbose syntax. I generally try to avoid this because it is a MySQL-specific extension to SQL that isn't generally supported elsewhere. CASE is standard SQL and is much more portable across different database engines, and I prefer to write portable queries as much as possible, only using engine-specific extensions when the portable alternative is considerably slower or less convenient.


MySQL also has IF():

SELECT   id, action_heading,       IF(action_type='Income',action_amount,0) income,       IF(action_type='Expense', action_amount, 0) expenseFROM tbl_transaction


Try to use IF(condition, value1, value2)

SELECT ID, HEADING, IF(action_type='Income',action_amount,0) as Income,IF(action_type='Expense',action_amount,0) as Expense