Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add column to SQL Server

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

like image 756
Antarr Byrd Avatar asked Apr 14 '11 16:04

Antarr Byrd


People also ask

How do I add a new column in SQL Server?

Use SQL Server Management Studio In Object Explorer, right-click the table to which you want to add columns and choose Design. Select the first blank cell in the Column Name column. Type the column name in the cell. The column name is a required value.

How do I add a column to an existing table query?

The basic syntax of an ALTER TABLE command to add a New Column in an existing table is as follows. ALTER TABLE table_name ADD column_name datatype; The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table is as follows.

Can you insert a column in SQL?

There is no SQL ADD COLUMN statement. To add a column to an SQL table, you must use the ALTER TABLE ADD syntax. ALTER TABLE lets you add, delete, or modify columns in a table. After you have created a table in SQL, you may realize that you forgot to add in a specific column that you need.


4 Answers

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.

like image 93
Martin Smith Avatar answered Oct 05 '22 03:10

Martin Smith


Use this query:

ALTER TABLE tablename ADD columname DATATYPE(size);

And here is an example:

ALTER TABLE Customer ADD LastName VARCHAR(50);
like image 27
bhavesh N Avatar answered Oct 05 '22 03:10

bhavesh N


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

like image 29
Alex K. Avatar answered Oct 05 '22 01:10

Alex K.


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
like image 44
Chiragkumar Thakar Avatar answered Oct 05 '22 03:10

Chiragkumar Thakar