Adding constraints for the existing table without any constraint names

We can place constraints on columns after creating the table but before inserting the values.

Note:

1. In Table Level constraints DEFAULT and NOT NULL constraints are not allowed.

2. The below approach is applicable only when there is no data available in the table.

Step1: Create any table with out any constraints

Example:CREATE TABLE DEPT (DEPTNO INT,DNAME VARCHAR(20),LOC VARCHAR(20))

Step2: Make a single column as NOT NULL for which we want provide Primary Key constraint.

Syntax: ALTER TABLE TABLENAME ALTER COLUMN COLUMNNAME DATATYPE NOT NULL

Example1: ALTER TABLE DEPT ALTER COLUMN DEPTNO INT NOT NULL.

Step3: Add your required constraints to columns expect DEFAULT and NOT NULL by using the following approach.

Syntax: ALTER TABLE TABLENAME ADD CONSTRAINTTYPE (COLUMN1),CONSTRAINTTYPE (COLUMN2),...

Example1: ALTER TABLE DEPT ADD PRIMARY KEY(DEPTNO),UNIQUE(DNAME)
Share/Bookmark

No comments: