626_Exchange Seats

Mary is a teacher in a middle school and she has a tableseatstoring students' names and their corresponding seat ids.

The column id is continuous increment.

Mary wants to change seats for the adjacent students.

Can you write a SQL query to output the result for Mary?

+---------+---------+
|    id   | student |
+---------+---------+
|    1    | Abbot   |
|    2    | Doris   |
|    3    | Emerson |
|    4    | Green   |
|    5    | Jeames  |
+---------+---------+

For the sample input, the output is:

+---------+---------+
|    id   | student |
+---------+---------+
|    1    | Doris   |
|    2    | Abbot   |
|    3    | Green   |
|    4    | Emerson |
|    5    | Jeames  |
+---------+---------+

Note: If the number of students is odd, there is no need to change the last one's seat.

Solution 1: change name

  • Left join seat table twice to get the previous name and the next name for each name

  • Use CASE WHEN to differentiate if we want to use the previous name or the next name

  • Use MOD(id, 2) = 0 or 1 to differentiate if the id is odd or even

  • Handle the last odd case if it exist with IFNULL() function

Solution 2: change id

For students with odd id, the new id is (id+1) after switch unless it is the last seat. And for students with even id, the new id is (id-1).

Solution 3: using two UNION operators

Last updated

Was this helpful?