Exchange Seats - Problem
Given a Seat table with columns id and student, write a SQL solution to swap the seat id of every two consecutive students.
Rules:
- If the number of students is odd, the id of the last student is not swapped
- Return the result table ordered by
idin ascending order
The table structure is:
Seat table:
id(int): Primary key, starts from 1 and increments continuouslystudent(varchar): Name of the student
Table Schema
Seat
| Column Name | Type | Description |
|---|---|---|
id
PK
|
int | Primary key, seat identifier starting from 1 |
student
|
varchar | Name of the student |
Primary Key: id
Note: The ID sequence always starts from 1 and increments continuously
Input & Output
Example 1 — Basic Seat Swapping
Input Table:
| id | student |
|---|---|
| 1 | Alice |
| 2 | Bob |
| 3 | Charlie |
| 4 | David |
| 5 | Eve |
Output:
| id | student |
|---|---|
| 1 | Bob |
| 2 | Alice |
| 3 | David |
| 4 | Charlie |
| 5 | Eve |
💡 Note:
Students are swapped in pairs: (1,2) swap to become (Bob,Alice), (3,4) swap to become (David,Charlie). Student 5 (Eve) has no pair, so remains in the same position.
Example 2 — Even Number of Students
Input Table:
| id | student |
|---|---|
| 1 | Alice |
| 2 | Bob |
Output:
| id | student |
|---|---|
| 1 | Bob |
| 2 | Alice |
💡 Note:
With an even number of students, all students have pairs. Alice and Bob swap positions completely.
Example 3 — Single Student
Input Table:
| id | student |
|---|---|
| 1 | Alice |
Output:
| id | student |
|---|---|
| 1 | Alice |
💡 Note:
With only one student, there's no one to swap with, so Alice remains in seat 1.
Constraints
-
1 ≤ id ≤ 50 -
studentis a non-empty string -
idis a continuous sequence starting from 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Original seat assignments
2
CASE WHEN
Apply swap logic
3
Output
Students in swapped seats
Key Takeaway
🎯 Key Insight: Use modulo operation to identify odd/even seats and conditionally swap with CASE WHEN logic
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code