A few days back while I was solving a problem at LeetCode, came across this problem Swap Salary. The problem was interesting when I have written an if-else condition like I do while coding. I never came across this type of interesting MySQL problem neither I had any work scenarios where I could have used such conditions. While browsing different websites and going through different resources I realized I should just write a blog on it, hope it helps everyone.

Case() is used to write conditions in the query with the if-else statement.

  • When a condition is true, it will stop reading and will return the result
  • If no conditions are true, it returns the value in the ELSE clause
  • If there is no ELSE part and no conditions are true, it will return a NULL
CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    WHEN conditionN THEN resultN
    ELSE result
END;

The problem in LeetCode asks for a solution where you need to swap the gender from m=f or vice versa. The solution is to write an update query with the case ().

update salary set sex = (case when sex = 'm' then 'f' else 'm' end);

Happy learning 💻💻

References: