The Swap Sex of Employees interview question is a SQL task that requires you to update a database table. You are given a table Salary with a column sex that contains values 'm' (male) and 'f' (female). The goal is to swap all 'f' values to 'm' and all 'm' values to 'f' using a single update statement and without using an intermediate temporary table.
This question is asked by companies like Meta and Amazon to test a candidate's knowledge of the SQL UPDATE statement and conditional logic. It evaluates whether you can use a CASE statement or an IF function within an update query. It's a test of writing efficient, concise SQL code to perform bulk updates based on existing values.
The primary pattern is the Database Update with Conditional Logic. The most standard way to solve this is using the UPDATE statement combined with a CASE expression:
UPDATE table_name SET column = CASE WHEN condition1 THEN result1 ELSE result2 END;
This allows the database to evaluate the condition for each row and apply the correct swap in a single pass.
Original Table:
A common mistake is trying to use two separate UPDATE statements (e.g., first change all 'm' to 'f', then all 'f' to 'm'). This fails because the first statement changes everything to 'f', and the second then changes everything back to 'm'. Another mistake is using a SELECT statement instead of an UPDATE statement, which doesn't actually persist the changes to the database.
For the Swap Sex of Employees coding problem, make sure you are comfortable with the CASE statement syntax in SQL. It is a powerful tool for performing complex updates and transformations. Also, understand the difference between DML (Data Manipulation Language) like UPDATE and DQL (Data Query Language) like SELECT.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Fix Names in a Table | Easy | Solve | |
| Not Boring Movies | Easy | Solve | |
| Primary Department for Each Employee | Easy | Solve | |
| Queries Quality and Percentage | Easy | Solve | |
| Sales Person | Easy | Solve |