Saturday, 7 October 2017

CHECK and DEFAULT Constraint

Create table with Check Constraint


Create a Table with CHECK and DEFAULT Constraint
CREATE TABLE MyDept1
 (
Deptno NUMBER(2)
   CONSTRAINT MyDept_Deptno_PK1 PRIMARY KEY
   CONSTRAINT MyDept_Deptno_CHK01 CHECK(Deptno IN(10, 20, 30, 40, 50, 60, 70, 80, 90)), DName VARCHAR2(16)
 DEFAULT 'Not Given'
 CONSTRAINT MyDept_DName_NN1 NOT NULL
 CONSTRAINT MyDept_DName_UNQ UNIQUE
 CONSTRAINT MyDept_DName_CHK01 CHECK(DName = UPPER(DName)),
Loc VARCHAR2(14)
 DEFAULT 'NOT GIVEN'
 CONSTRAINT MyDept_Loc_NN1 NOT NULL
 CONSTRAINT MyDept_Loc_CHK01 CHECK(Loc IN('NEW YORK', 'BOSTON', 'CHICAGO', 'NOT GIVEN','DALLAS'))
);




Insert Data into MyDept1 Table
INSERT INTO MyDept1 VALUES(10, 'ACCOUNTING', 'NEW YORK');
INSERT INTO MyDept1 VALUES(1, 'ACCOUNTING', 'NEW YORK');
INSERT INTO MyDept
 *
ERROR at line 1: ORA-02290: check constraint (SCOTT.MYDEPT_DEPTNO_CHK01) violated.


This Record we are Inserting for DEFAULT Constraint
INSERT INTO MyDept1 (Deptno, DName) VALUES(20, 'OPERATIONS');


Now check your table data, while Inserting deptno=20 record we didn't provide the LOC value but while creating the table we set  DEFAULT value as 'NOT GIVEN'.








No comments:

Post a Comment