How to Add, Delete or Rename a Column in a Table Using SQL

Category : Tips User Rating : 3.5 Stars      Views : 3.5 Stars
One Click Feedback
Please help us to improve the site by rating the quality of this article by clicking a button below.
In many circumstances columns in a table can be removed, added or renamed without having to drop and recreate the table.

By way of example I’ll create a table and then populate it with a couple of rows of data :

CREATE TABLE Table1
(
Column1 INT NOT NULL,
Column2 VARCHAR(5) NULL,
Column3 VARCHAR(20) NOT NULL,
Column4 VARCHAR(50) NOT NULL,
Column5 DATETIME NOT NULL
)
GO
 
INSERT INTO Table1 (Column1,Column2,Column3,Column4,Column5)
SELECT 1,'Mr','Fred','Bloggs','23 Dec 1962' UNION
SELECT 2,'Mrs','Freda','Bloggs','10 Jan 1964'

Adding Columns

To add columns simply define the column name and datatype (e.g. VARCHAR(100)) with the following syntax :
ALTER TABLE Table1 ADD Column6 VARCHAR(100) NULL
There are some restrictions around adding columns, for instance the column has to be NULLable if it doesn't have a default defined.

Deleting Columns

A similar syntax to that above can be used to drop an existing column :
ALTER TABLE Table1 DROP COLUMN Column2

Renaming Columns

You can also rename an existing column, though curiously this is not supported by the ALTER TABLE syntax and instead we will need to use the sp_rename stored procedure :
exec sp_rename 'Table1.Column1','ID','COLUMN'
exec sp_rename 'Table1.Column5','DateOfBirth','COLUMN'
The last parameter specifies the object type to be renamed, in this case a column. There are circumstance where columns cannot be dropped or renamed, for instance you can't rename (or indeed delete) a column if it has a constraint defined on it. You'll notice the following warning message when running sp_rename in SQL Server Management Studio. However there's nothing to worry about, this is only a warning and the column will still get renamed! sp_rename

Link back to this article : https://www.sqlmatters.com/Articles/How to Add, Delete or Rename a Column in a Table Using SQL.aspx

Keywords

SQL,datatype,column


Comments
Post by sengha on Sun 18 Jun 2023 18:00. Report Inappropriate Post

i got a clear understanding

Post a comment   No login required !

Name : Email : Website :
Will be displayed alongside your comment
Not displayed Optional, but displayed if entered