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 id in ascending order

The table structure is:

Seat table:

  • id (int): Primary key, starts from 1 and increments continuously
  • student (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
  • student is a non-empty string
  • id is a continuous sequence starting from 1

Visualization

Tap to expand
Exchange Seats Problem OverviewBefore Swapping1Alice2Bob3Charlie4David5EveSwap PairsAfter Swapping1Bob2Alice3David4Charlie5EveNo pair - stays sameOdd positions (1,3,5)Even positions (2,4)
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
Asked in
Facebook 12 Microsoft 8
28.5K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen