Magicsheet logo

Swap Sex of Employees

Easy
12.5%
Updated 8/1/2025

Asked by 4 Companies

Topics

Swap Sex of Employees

What is this problem about?

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.

Why is this asked in interviews?

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.

Algorithmic pattern used

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.

Example explanation

Original Table:

  • ID 1: sex 'm'
  • ID 2: sex 'f'
  • ID 3: sex 'f' After the update:
  • Row 1: sex was 'm', so it becomes 'f'.
  • Row 2: sex was 'f', so it becomes 'm'.
  • Row 3: sex was 'f', so it becomes 'm'. The result is a table where every 'm' is now 'f' and every 'f' is now 'm'.

Common mistakes candidates make

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.

Interview preparation tip

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.

Similar Questions