sabarish sabarish - 2 months ago 7
PHP Question

how to use if condition inside a mysql UPDATE query?

i want to update my database field with if condition. i tried lot of combination with update query but still no luck. i want to something like this..

UPDATE SET tbl dep_mas_id= if(dep_mas_id==Management){'1'}if(dep_mas_id==Finance){'3'}


any help would be really great.

Answer

You can use CASE WHEN EXPRESSION

UPDATE
YOUR_TABLE
SET dep_mas_id = (
    CASE
    WHEN dep_mas_id = 'Management' THEN
        '1'
    WHEN dep_mas_id = 'Finance' THEN
        '3'
    ELSE
        dep_mas_id
    END
)

Check How to use Mysql SELECT CASE WHEN expression