Skip to content
Related Articles

Related Articles

Improve Article
Swap Column Values in SQL Server
  • Difficulty Level : Medium
  • Last Updated : 05 Nov, 2020

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
AnkitGuptaDelhiankit@gfg.org
BabitaDuttaNoidababita@gfg.org
ChetanJainNoidachetan@gfg.org
IshaSharmaDelhiisha@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 :

FirstNameLastNameCityEmail
AnkitGuptaDelhiankit@gfg.org
BabitaDuttaNoidababita@gfg.org
ChetanJainNoidachetan@gfg.org
IshaSharmaDelhiisha@gfg.org
My Personal Notes arrow_drop_up
Recommended Articles
Page :