Hi everyone! π
I'm starting this dev journal to track my weekly progress in software development and problem solving. Iβm currently focusing on strengthening my foundations in Data Structures, Algorithms, and Database SQL through platforms like LeetCode.
This journal is not only to document what I solve, but also how I think, improve, and learn β and hopefully, someone else finds it useful too!
First Problem: Swapping 'm' and 'f' in SQL
This week's problem was from LeetCode:
Goal: Swap all 'm' and 'f' values in the sex column using a single SQL update statement, without using any intermediate tables or SELECT queries.
Here's the table:
Table: Salary
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| id | int |
| name | varchar |
| sex | ENUM |
| salary | int |
+-------------+----------+
Input:
+----+------+-----+--------+
| id | name | sex | salary |
+----+------+-----+--------+
| 1 | A | m | 2500 |
| 2 | B | f | 1500 |
| 3 | C | m | 5500 |
| 4 | D | f | 500 |
+----+------+-----+--------+
Output:
+----+------+-----+--------+
| id | name | sex | salary |
+----+------+-----+--------+
| 1 | A | f | 2500 |
| 2 | B | m | 1500 |
| 3 | C | f | 5500 |
| 4 | D | m | 500 |
+----+------+-----+--------+
π£ My Approaches
πΉ First Attempt (Basic CASE logic)
UPDATE Salary
SET sex = CASE
WHEN sex = 'm' THEN 'f'
WHEN sex = 'f' THEN 'm'
END;
It worked fine, but I wondered if I could simplify it.
πΈ Second Attempt (Shorter CASE)
SET sex = CASE
WHEN sex = 'm' THEN 'f'
ELSE 'm'
END;
This still gave the correct result β because sex only has 'm' and 'f', so ELSE 'm' is safe.
π’ Final Attempt (IF-based)
UPDATE Salary
SET sex = IF(sex = 'm', 'f', 'm');
This version is short, clean, and very readable. I believe it's the most efficient and expressive for this case.
β I'm sticking with this as my final version (unless there's a hidden SQL performance nuance I missed β feel free to comment!).
π Reflection
Even a simple-looking problem made me think about different ways to write conditional updates. This helped me:
Practice CASE vs IF
Learn how to simplify logic without breaking correctness
Think about readability and maintainability in SQL
Thatβs it for this week!
Next time, Iβll share more problems, learnings, and maybe some frontend/devlog thoughts too. Thanks for reading! π»β¨
Top comments (2)
While CASE is the standard way to handle conditional updates, some database systems like MySQL offer specialized functions. For instance, MySQL provides the IF() function, which acts like a shorthand conditional expression.
Syntax
UPDATE table_name
SET column_name = IF(condition, value_if_true, value_if_false);
Some comments may only be visible to logged-in visitors. Sign in to view all comments.