Thursday, November 26, 2015

SQL CHECK

SQL CHECK constraint check specified specific condition, which must evaluate to true for constraint to be satisfied.
SQL CHECK constraint must be specified as a logical expression that evaluated specific condition either TRUE or FALSE.
SQL CHECK constraint define at column level that allow only specified values for a column and Whereas define at table level that allow specified values as well as use other column value for checking specific condition.
 CREATE TABLE student_info(
  no NUMBER(3) PRIMARY KEY,
  stu_code VARCHAR(10) CHECK (stu_code like 'pr%'),
  name VARCHAR(30) CHECK ( name = upper(name) ),
 city VARCHAR(30) CHECK (city IN ('LUcknow','DELHI','KANPUR'))
 scholarship NUMBER(5) CHECK (scholarship BETWEEN 500 AND 20000)
);
We are create new student_info table name with following check constraints:
  • Values inserted into stu_code column must be start with the lower letter 'pr'.
  • Values inserted into name column must be capitalize.
  • Values inserted into city column only allow lucknow,kanpur,delhi as valid legitimate values.
  • Values inserted into scholarship column between 500 and 20000.

ADD CHECK constraint (ALTER TABLE)

ALTER TABLE statement to add CHECK constraint in existing table column.
Syntax :
ALTER TABLE table_name
 ADD CONSTRAINT check_constraint_name CHECK (column_name condition);
ALTER TABLE student_info ADD CONSTRAINT check_name CHECK (name = upper(name));

DROP CHECK constraint (ALTER TABLE)

ALTER TABLE statement to drop CHECK constraint in existing table column.
Syntax :
ALTER TABLE table_name
 DROP CONSTRAINT check_constraint_name;

No comments:

Post a Comment