Add Column Constraint

To add a constraint to an existing table use the alter table statement with the add constraint command. There are four different types of constraints:

  1. Primary Key Constraints – Enforces unique values for specified column, can be referenced.
  2. Foreign Key Constraints – Enforces a reference to a primary key
  3. Unique Constraints – Ensures unique values within a column
  4. Check Constraints – Limits values acceptable for a column based on an evaluation

Add unique constraint

[cc lang=”sql”]
ALTER TABLE dbo.Presidents
ADD CONSTRAINT President_unique UNIQUE (President)
[/cc]

Add constraint to test value

[cc lang=”sql”]
ALTER TABLE dbo.Presidents
ADD CONSTRAINT President_unique CHECK (YearsInOffice >= 0 AND YearsInOffice < 13) [/cc]

4 comments
Justin 25 Oct 2013 at 5:45 am

The column that you added the constraint to already existed. Can you add a column and a constraint in one statement?

Anonymous 17 Jan 2012 at 3:00 am

whic tag is used to add columns in a table

Anonymous 11 Feb 2011 at 9:42 pm

can i alter the order of the columns in a table

Derek Dieter 17 Feb 2011 at 1:45 pm

Hi, unfortunately you cannot. You have to drop and recreate the table.

Featured Articles

 Site Author

  • Thanks for visiting!