Alter Table Add Column

Adding a column to a table in SQL Server is done using the ALTER TABLE tablename ADD command. When adding columns you can specify all the same settings available when creating a table.

In the example below, we will create a small sample table, then add columns using the ALTER TABLE command.

Multiple columns can be specificied by using the syntax below. First issue an alter table command then add the column name, data type, nullable, and default value.

IF OBJECT_ID('tempdb..#employees') IS NOT NULL
BEGIN
    DROP TABLE #employees
END

CREATE TABLE #employees
(
    EmployeeID INT IDENTITY (1,1) CONSTRAINT PK_employee NOT NULL PRIMARY KEY CLUSTERED
    ,FirstName VARCHAR(50)
)
GO

INSERT INTO #employees (FirstName) VALUES ('John');
 
ALTER TABLE #employees
ADD
     LastName VARCHAR(50) NULL
    ,SSN VARCHAR(9) NULL CONSTRAINT ssn_unique UNIQUE
    ,IsTerminated bit NOT NULL DEFAULT 0
    ,DateAdded datetime NOT NULL DEFAULT GETDATE()
    ,DateModified DATETIME NULL DEFAULT GETDATE()
    ,Comments VARCHAR(255) SPARSE NULL -- SQL Server 2008 sparse column
   
SELECT * FROM #employees
When adding a column to an existing table the ordinal position will always be appended to the end

Also note, when you add columns with a default value, the value will only get populated when you specify the column as NOT NULL. Otherwise, NULL values will populate the column initially. However once the column is created, subsequent insert statements will populate the default value. In the above example, DateAdded is initially populated whereas DateModified is only populated after a row is inserted.

Please help improve this content! Please write a comment below about what’s missing!

2 comments
Dave 05 Nov 2014 at 9:43 pm

Great info. Presented well. One caveat, what if I wanted to add a set of columns to every relative table in the database. Would you suggest a For @each in ‘systables.*’ and add the columns for the @each table point? What is your take on it. The reason I ask is I am adding audit information to each table for who added/updated it. Your example of the dates is great along with the explanation. Also didn’t know about the sparse tag. Thanks.

najib 25 Jun 2014 at 11:09 am

ok i found this info here usefull and simple to understand thank you

Featured Articles

 Site Author