DDSA Solutions

627. Swap Salary

Problem Overview

Swap every employee sex from m to f and f to m in one SQL UPDATE.

Intuition

Swap every employee sex from m to f and f to m in one SQL UPDATE. Use CASE or IF — no temporary column needed.

Algorithm

  1. 1UPDATE Salary SET sex = CASE WHEN sex = 'm' THEN 'f' ELSE 'm' END;
  2. 2Alternatively: SET sex = IF(sex = 'm', 'f', 'm').
  3. 3Single statement updates all rows atomically.

Example Walkthrough

Input: Rows with sex m and f mixed

  1. 1.Each m becomes f; each f becomes m in one pass.

Output: All sex values toggled

Common Pitfalls

  • Assume only m and f appear in the column.
  • One UPDATE — no temp table required.
  • CASE must cover both branches.
627.sql
MySQL
UPDATE Salary
SET sex = CASE WHEN sex = 'm' THEN  'f' ELSE  'm' END;
Was this solution helpful?

Related Problems