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 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.

Next: SQL DROP CONSTRAINT

This page was last updated on June 19, 2023.




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