How to swap two elements in different columns in SQL

Swapping is a technique in which the values of two variables are exchanged. To swap two elements in different columns in SQL, we must first create a table and insert some rows. The table below is a sample table containing three attributes—id, FName, and LName—of five students.

We will swap the first name and last name of the student whose id is equal to 1.

Before swap

Before the swap, the first name contains “Ali,” and the last name contains “Asghar.”

id

FName

LName

1

Ali

Asghar

2

Wahid

Ali

3

Ahmed

Yasser

4

Ali

Sultan

5

Dian

Suqlain

After swap

After the swap, the first name will contain “Asghar” and the last name will contain “Ali.”

id

FName

LName

1

Asghar

Ali

2

Wahid

Ali

3

Ahmed

Yasser

4

Ali

Sultan

5

Dian

Suqlain

Swapping process

The logic of swapping two elements is the same in SQL as in other programming languages. To swap two elements, we need to follow the steps mentioned below:

  1. Save the value of the first element in a temporary variable.
  2. Assign the second element to the first element.
  3. Assign the temporary variable to the second element.

The code below is the implementation of the process described above:

-- Step 1: Store the value of FName in a temporary variable
SET @temp = (SELECT FName FROM Student WHERE id = 1);
-- Step 2: Update the values of FName and LName, swapping their values
UPDATE Student
SET FNAme = LName,
LName = @temp
WHERE id = 1;
-- Show the values of FName and LName, after swapping their values
select * from Student;
Swap two elements

Code explanation

Here is the line-by-line explanation of the code given above:

  • Line 2: Stores the value of FName into temp where the id is 1.

  • Lines 6: Stores the value of LName into FName.

  • Lines 7: Stores the value of temp into LName.

  • Line 8: Conditional statement ensures that the values of the specific row are swapped where the id is equal to 1.

  • Line 11: After swapping the values, prints the table to check whether the values have been swapped.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved