Open In App

Swap Column Values in SQL Server

Last Updated : 05 Nov, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
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 :
LastNameFirstNameCityEmail
AnkitGuptaDelhi[email protected]
BabitaDuttaNoida[email protected]
ChetanJainNoida[email protected]
IshaSharmaDelhi[email protected]
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 :
FirstNameLastNameCityEmail
AnkitGuptaDelhi[email protected]
BabitaDuttaNoida[email protected]
ChetanJainNoida[email protected]
IshaSharmaDelhi[email protected]

Next Article
Article Tags :

Similar Reads