SQL > ALTER TABLE > Add Constraint Syntax

Sometimes we may decide to add a new constraint to an existing table (to see what are the different types of constraints that can be placed on a database table, please refer to the CONSTRAINT section).

The ALTER TABLE ADD CONSTRAINT statement allows you to enforce data integrity rules — such as UNIQUE, PRIMARY KEY, or FOREIGN KEY — on an existing table without recreating it.

The syntax for adding a constraint in SQL is,

ALTER TABLE "table_name"
ADD [CONSTRAINT_NAME] [CONSTRAINT_TYPE] [CONSTRAINT_CONDITION];

Let's look at the example. Assuming our starting point is the Customer table created in the CREATE TABLE section:

Table Customer

 Column Name  Data Type 
 First_Name  char(50) 
 Last_Name  char(50) 
 Address  char(50) 
 City  char(50) 
 Country  char(25) 
 Birth_Date  datetime 

Assume we want to add a UNIQUE constraint to the "Address" column. To do this, we type in the following:

MySQL:

ALTER TABLE Customer ADD CONSTRAINT Con_First UNIQUE (Address);

Oracle:

ALTER TABLE Customer ADD CONSTRAINT Con_First UNIQUE (Address);

SQL Server:

ALTER TABLE Customer ADD CONSTRAINT Con_First UNIQUE (Address);

where Con_First is the name of the constraint.

Frequently Asked Questions

Q: What types of constraints can I add with ALTER TABLE ADD CONSTRAINT?
A: You can add UNIQUE, PRIMARY KEY, FOREIGN KEY, and CHECK constraints to an existing table using ALTER TABLE ADD CONSTRAINT.
Q: Do I need to name a constraint when adding it?
A: Naming a constraint is optional in most databases, but it is highly recommended. A named constraint is much easier to reference when you need to drop or modify it later.
Q: What happens if I add a UNIQUE constraint to a column that already has duplicate values?
A: The operation will fail. The database enforces the constraint immediately, so all existing data must already satisfy the constraint before it can be added.
Q: How do I add a PRIMARY KEY constraint to an existing table?
A: Use: ALTER TABLE Customer ADD CONSTRAINT PK_Customer PRIMARY KEY (First_Name, Last_Name);

Next: SQL DROP CONSTRAINT

This page was last updated on March 19, 2026.




Copyright © 2026   1keydata.com   All Rights Reserved     Privacy Policy     About   Contact