ADD and DROP a Constraint using ALTER TABLE command in SQL

For Complete YouTube Video: Click Here

In this class, we will understand ADD and DROP a Constraint using ALTER TABLE command in SQL.

We have already discussed the concepts of ADD, DROP, and MODIFY columns of a table.

ADD and DROP a Constraint using ALTER TABLE command in SQL

This class will understand how to ADD and DROP a Constraint using ALTER TABLE command in SQL.

To understand, we will consider the user’s table as shown below.

ADD and DROP a Constraint using ALTER TABLE command in SQL
ADD and DROP a Constraint using ALTER TABLE command in SQL

The above is what we have considered in our previous class.

We haven’t created a primary key for the user’s table.

We will now alter the table by adding the id column as the primary key.

ADD Constraint

ALTER TABLE users ADD CONSTRAINT pk_users PRIMARY KEY (id);

In the above command, ADD CONSTRAINT is the keyword used to add a constraint.

Whenever we add a constraint, we have to give the name of the ‘constraint.’

In our case, we have given the name pk_users.

These names are significant because they are used in future to change the constraints.

The new constraint has been added.

To check whether the constraint has been altered, let us insert the row as shown below.

The image below is the error message generated because the value 2555 is already existing in the table.

ADD and DROP a Constraint using ALTER TABLE command in SQL 1
ADD and DROP a Constraint using ALTER TABLE command in SQL 1

DROP Constraint

ALTER TABLE users DROP CONSTRAINT pk_users;

The DROP CONSTRAINT is the keyword used to drop the constraint.

In the above command, the constraint name has been used.

By executing the above command, the primary key constraint will get dropped.

To check whether the constraint has been dropped or not, we will insert the row as shown below.

ADD and DROP a Constraint using ALTER TABLE command in SQL 2
ADD and DROP a Constraint using ALTER TABLE command in SQL 2

Even though the id value exists in the id column, the row will get inserted.