The MySQL If and Case Statement Exercise: How to Swap Elements in MySQL?


Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update statement and no intermediate temp table.

Note that you must write a single update statement, DO NOT write any select statement for this problem.

Example:

| id | name | sex | salary |
|----|------|-----|--------|
| 1  | A    | m   | 2500   |
| 2  | B    | f   | 1500   |
| 3  | C    | m   | 5500   |
| 4  | D    | f   | 500    |

After running your update statement, the above salary table should have the following rows:

| id | name | sex | salary |
|----|------|-----|--------|
| 1  | A    | f   | 2500   |
| 2  | B    | m   | 1500   |
| 3  | C    | f   | 5500   |
| 4  | D    | m   | 500    |

SQL Schema

1
2
3
4
5
6
create table if not exists salary(id int, name varchar(100), sex char(1), salary int)
Truncate table salary
insert into salary (id, name, sex, salary) values ('1', 'A', 'm', '2500')
insert into salary (id, name, sex, salary) values ('2', 'B', 'f', '1500')
insert into salary (id, name, sex, salary) values ('3', 'C', 'm', '5500')
insert into salary (id, name, sex, salary) values ('4', 'D', 'f', '500')
create table if not exists salary(id int, name varchar(100), sex char(1), salary int)
Truncate table salary
insert into salary (id, name, sex, salary) values ('1', 'A', 'm', '2500')
insert into salary (id, name, sex, salary) values ('2', 'B', 'f', '1500')
insert into salary (id, name, sex, salary) values ('3', 'C', 'm', '5500')
insert into salary (id, name, sex, salary) values ('4', 'D', 'f', '500')

This can be solved using three method: the IF, and the case statement in MySQL database.

SQL If Statement to Swap

IF function takes three parameters in MYSQL, the boolean condition, and the expression when boolean is evaluated to true, and the third is the expression when boolean expression is evaluated to false.

1
UPDATE salary SET sex = IF(sex='m','f','m');
UPDATE salary SET sex = IF(sex='m','f','m');

SQL Case Statement to Swap

The case statment is a bit like switch in modern programming languages such as C++. You can have multiple WHEN (corresponds to case) statements and one ELSE (default) in MySQL.

1
2
3
4
5
6
UPDATE salary
SET
    sex = CASE sex
        WHEN 'm' THEN 'f'
        ELSE 'm'
    END;
UPDATE salary
SET
    sex = CASE sex
        WHEN 'm' THEN 'f'
        ELSE 'm'
    END;

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
383 words
Last Post: Compute the Number of Ways to Paint the House via Dynamic Programming Algorithm
Next Post: How to Design a Two-Sum Data Structure?

The Permanent URL is: The MySQL If and Case Statement Exercise: How to Swap Elements in MySQL?

Leave a Reply