← Back to SQL, page 10

sql-0194 · Medium mid

How do you swap the values of two columns in every row with a single UPDATE?

Write UPDATE t SET a = b, b = a. In standard SQL, SQLite and PostgreSQL, every expression on the right side sees the row's old values, so the swap works without a temporary variable. MySQL evaluates assignments left to right and would set both columns to the old b (not run here).

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;
idab
12010
24030

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;
idab
12010
24030

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