Swap Column Values in SQL Server
Introduction (Swap Column Values in SQL Server) :
If you are a developer and have learned the programming languages, you might think that you will need a third variable or another temporary storage location to swap the values. Here, as you are a SQL Server DBA, you can simply swap them using a single update statement.
Example and Application features :
It happens that SQL user might enter incorrect values in the database columns, the next task is to swap those values.
Syntax :
Syntax to write a query to swap column values in SQL server.
UPDATE [tablename] SET [col1] = [col2], [col2] = [col1] GO
Let us suppose we need to swap columns in any table in the SQL server.
Example –
Let us suppose we have below the table “geek_demo”.
Select * from geek_demo ;
Output :
LastName | FirstName | City | |
---|---|---|---|
Ankit | Gupta | Delhi | ankit@gfg.org |
Babita | Dutta | Noida | babita@gfg.org |
Chetan | Jain | Noida | chetan@gfg.org |
Isha | Sharma | Delhi | isha@gfg.org |
Now, to update the column or to swap the column used the following query given below.
UPDATE [geek_demo] SET [FirstName] = [LastName], [LastName] = [FirstName] GO
Now, let’s see the output.
Select * from geek_demo ;
Output :
FirstName | LastName | City | |
---|---|---|---|
Ankit | Gupta | Delhi | ankit@gfg.org |
Babita | Dutta | Noida | babita@gfg.org |
Chetan | Jain | Noida | chetan@gfg.org |
Isha | Sharma | Delhi | isha@gfg.org |
Contact Us