Exchange Seats
Swap the student in each adjacent pair of seats.
Start practiceProblem statement
Prompt
Given the seat table below, write a query that swaps the student of every adjacent pair of seats — seat 1 swaps with seat 2, seat 3 with seat 4, and so on.
- If the last seat has an odd id (no partner), that student stays in place.
- The result must be ordered by `id`.
- Output columns:
idandstudent.
Example
| id | student |
|---|---|
| 1 | Abbot |
| 2 | Doris |
| 3 | Emerson |
| 4 | Green |
Expected result:
| id | student |
|---|---|
| 1 | Doris |
| 2 | Abbot |
| 3 | Green |
| 4 | Emerson |
Constraints
seat.idis the primary key and is contiguous (no gaps).
Tips
CASE WHEN id % 2 = 1 THEN id + 1 ELSE id - 1 ENDgives the partner's id.- Use a
LEFT JOINor correlated subquery to fetch the partner's student; when the partner is missing (last odd seat), keep the original student.
Schema
CREATE TABLE seat (
id INTEGER PRIMARY KEY,
student TEXT NOT NULL
);
Sample data
INSERT INTO seat (id, student) VALUES
(1, 'Abbot'),
(2, 'Doris'),
(3, 'Emerson'),
(4, 'Green'),
(5, 'Jeames');
Additional hidden fixtures are applied during validation to test edge cases.
Solution
One correct approach — try solving it yourself in the practice editor first, then compare. There is usually more than one valid solution.
-- Reference: swap adjacent pairs; odd tail stays put.
SELECT s1.id,
COALESCE(s2.student, s1.student) AS student
FROM seat s1
LEFT JOIN seat s2
ON s2.id = CASE
WHEN s1.id % 2 = 1 THEN s1.id + 1
ELSE s1.id - 1
END
ORDER BY s1.id;
Key concepts
- CASE WHEN
- Odd/even
- Correlated subquery
Related questions
- mediumCustomers Who Bought All ProductsFind customers who have purchased every product in the catalogue.
- easyCustomers Without OrdersList customers who have never placed an order using an anti-join.
- mediumImmediate Food DeliveryReport the percentage of customers' first orders that were delivered immediately.
- mediumNth Highest SalaryReturn the third-highest distinct salary, or NULL when it does not exist.
- mediumPivot Quarterly SalesPivot per-year sales rows into one row per year with a column per quarter.