Full answer
sql
CREATE TABLE pairs (id INTEGER PRIMARY KEY, a INTEGER, b INTEGER);
INSERT INTO pairs VALUES (1, 10, 20), (2, 30, 40);
UPDATE pairs SET a = b, b = a;
SELECT * FROM pairs ORDER BY id;| id | a | b |
|---|---|---|
| 1 | 20 | 10 |
| 2 | 40 | 30 |
Both assignments read the values from before the update, so the two columns trade places.
PostgreSQL agrees:
sql
CREATE TABLE pairs (id int PRIMARY KEY, a int, b int);
INSERT INTO pairs VALUES (1, 10, 20), (2, 30, 40);
UPDATE pairs SET a = b, b = a;
SELECT * FROM pairs ORDER BY id;| id | a | b |
|---|---|---|
| 1 | 20 | 10 |
| 2 | 40 | 30 |
The same rule makes SET qty = qty + 1, total = qty * price use the old qty in the second expression. Write such updates with that in mind, or compute from the new value explicitly (total = (qty + 1) * price).
sql
CREATE TABLE pairs (id INTEGER PRIMARY KEY, a INTEGER, b INTEGER);
INSERT INTO pairs VALUES (1, 10, 20), (2, 30, 40);
UPDATE pairs SET a = b, b = a;
SELECT * FROM pairs ORDER BY id;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- Right-hand expressions see old row values
- SET a = b, b = a swaps in one statement
- Later assignments do not see earlier ones
- MySQL differs and evaluates left to right
Common mistakes
- Using a temporary column for a swap that one UPDATE can do
- Expecting a second assignment to use the first one's new value
Follow-ups
- How would you swap two rows' values, such as ranks 1 and 2?
- What does SET qty = qty + 1, total = qty * price compute?
Tips
- State the old-values rule