Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ALTER TABLE to add a new column and make it unique?

How do I use ALTER TABLE to add a new column and make it unique?

like image 815
Innova Avatar asked Sep 17 '10 11:09

Innova


People also ask

How do I add a unique column to a table in SQL?

The syntax for creating a unique constraint using an ALTER TABLE statement in SQL Server is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n);

How will you alter a table and add a new column to it?

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 you use alter to add a column?

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.

How do you make a column unique in MySQL?

The syntax for creating a unique constraint using an ALTER TABLE statement in MySQL is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.


2 Answers

Depends on the DBMS, but I think the following is quite portable:

ALTER TABLE table_name ADD column_name datatype
ALTER TABLE table_name ADD UNIQUE (column_name)

If you want to give a name to the UNIQUE constraint, you could replace the last command with this:

ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column_name)
like image 120
Daniel Vassallo Avatar answered Oct 17 '22 12:10

Daniel Vassallo


if table is empty

  ALTER TABLE ADD (FieldName Type)
  ALTER TABLE ADD CONSTRAINT UNIQUE(FieldName)

If you have data in table you need to this in three steps:

  1. Add column
  2. Fill values
  3. Add unique constraint
like image 5
Michael Pakhantsov Avatar answered Oct 17 '22 12:10

Michael Pakhantsov