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:
- Save the value of the first element in a temporary variable.
- Assign the second element to the first element.
- 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 variableSET @temp = (SELECT FName FROM Student WHERE id = 1);-- Step 2: Update the values of FName and LName, swapping their valuesUPDATE StudentSET FNAme = LName,LName = @tempWHERE id = 1;-- Show the values of FName and LName, after swapping their valuesselect * from Student;
Code explanation
Here is the line-by-line explanation of the code given above:
-
Line 2: Stores the value of
FNameintotempwhere theidis1. -
Lines 6: Stores the value of
LNameintoFName. -
Lines 7: Stores the value of
tempintoLName. -
Line 8: Conditional statement ensures that the values of the specific row are swapped where the
idis equal to1. -
Line 11: After swapping the values, prints the table to check whether the values have been swapped.
Free Resources