Adding constraints for the existing table with constraint names

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 CONSTRAINT CONSTRAINTNAME CONSTRAINTTYPE (COLUMN1),CONSTRAINT CONSTRAINTNAME CONSTRAINTTYPE (COLUMN2,..........

Example: ALTER TABLE DEPT ADD CONSTRAINT PK PRIMARY KEY (DEPTNO),CONSTRAINT UQ UNIQUE(DNAME)
Share/Bookmark

No comments: