117

I need to add a column to my SQL Server table. Is it possible to do so without losing the data, I already have?

Thom A
  • 88,727
  • 11
  • 45
  • 75
Antarr Byrd
  • 24,863
  • 33
  • 100
  • 188

5 Answers5

182

Of course! Just use the ALTER TABLE... syntax.

Example

ALTER TABLE YourTable
  ADD Foo INT NULL /*Adds a new int column existing rows will be 
                     given a NULL value for the new column*/

Or

ALTER TABLE YourTable
  ADD Bar INT NOT NULL DEFAULT(0) /*Adds a new int column existing rows will
                                    be given the value zero*/

In SQL Server 2008 the first one is a metadata only change. The second will update all rows.

In SQL Server 2012+ Enterprise edition the second one is a metadata only change too.

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
20

Use this query:

ALTER TABLE tablename ADD columname DATATYPE(size);

And here is an example:

ALTER TABLE Customer ADD LastName VARCHAR(50);
AndrewRalon
  • 496
  • 1
  • 9
  • 24
bhavesh N
  • 787
  • 3
  • 9
  • 27
  • 1
    If you post code, XML or data samples, **please** highlight those lines in the text editor and click on the "code samples" button ( `{ }` ) on the editor toolbar to nicely format and syntax highlight it! – marc_s Apr 14 '11 at 20:43
3

Add new column to Table

ALTER TABLE [table]
ADD Column1 Datatype

E.g

ALTER TABLE [test]
ADD ID Int

If User wants to make it auto incremented then

ALTER TABLE [test]
ADD ID Int IDENTITY(1,1) NOT NULL
Chiragkumar Thakar
  • 3,616
  • 5
  • 37
  • 49
3

Adding a column using SSMS or ALTER TABLE .. ADD will not drop any existing data.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
0

Add new column to Table with default value.

ALTER TABLE NAME_OF_TABLE
ADD COLUMN_NAME datatype
DEFAULT DEFAULT_VALUE