CSE 880 Database Systems Database Constraints 1 Introduction 1. CON ST RAIN T S: Constraints are general restrictions on the data in the database. 2. Three Important Components (a) Event: Execution of insert, delete and update function on a table. (b) Condition: Restrictions on the data in the database defined by the database system or user-procedure. (c) Action: When the Condition is satisfied, certain action is taken by the database system or by userprocedure. 3. When an event occurs, condition is checked and if the condition is true the action is executed. 2 Built-in Constraints, Assertions and Triggers 1. BU ILT IN CON ST RAIN T : Both the condition and the action are system defined and is created at the time the table is created using CREAT E T ABLE command. Example: CREATE TABLE Student( Sid NUMBER (5) CONSTRAINT PK_Student PRIMARY KEY, Sname VARCHAR2 (30), ------- ); 2. ASSERT ION : Here the condition is user defined (not built-in) and the action is system defined. Example: A student must take at least two courses: For example, will not allow a student to delete the last second course. CREATE ASSERTION EnrollmentControl CHECK (Exists( Select count(*) From StudentCourse Group by sno Having count(cno)<2)) Assertion is invoked as a result of insert, delete or update events. CHECK provides the condition and when the 3 condition is true violation occurs and the action is taken by the system which is to prevent the event from taking place. 3. T RIGGERS: User defines the condition and the action. Example: Enter the inserted student record into the table EastLansingStudents if the inserted student’s address is East Lansing. CREATE TRIGGER InsertStudent AFTER INSERT ON Student FOR EACH ROW WHEN (NEW.Saddr="East Lansing") BEGIN INSERT INTO TABLE EastLansingStudents(Sid, Sname, Saddr, Sdno) (NEW.Sid, NEW.Sname, NEW.Saddr, NEW.Sdno) END 4 Constraints in Oracle 1. P RIM ARY KEY : A single or a set of columns of a table with unique or mandatory value. A table can be defined without a primary key. Example: CREATE TABLE Student( Sid NUMBER (5) CONSTRAINT PK_Student PRIMARY KEY, Sname VARCHAR2 (30), Saddr VARCHAR2 (30), Sdno NUMBER(3), LisenceNo VARCHAR2(10)); 2. Attribute level constraint versus table level constraint: For concatenated keys the constraint has to be defined for more than one attributes. Therefore, it cannot be defined on each attribute separately, requiring a table level constraint definition. example: Concatenated Primary key CONSTRAINT P K StudentCourse PRIMARY KEY (sid, cid) Attribute values of the concatenated key can be NULL but at least one of the attribute values must be NOT 5 NULL. Any of the columns of the concatenated key can be made NOT NULL explicitly by declaring NOT NULL against that attribute definition. 6 3. U N IQU E: All values in a column or columns must be unique (allows NULL) Example: CREATE TABLE Student( Sid NUMBER (5) CONSTRAINT PK_Student PRIMARY KEY, Sname VARCHAR2 (30), Saddr VARCHAR2 (30), Sdno NUMBER(3), LisenceNo VARCHAR2(10) UNIQUE); 4. N OT N U LL: Guarantees that a column has a value (i.e., value cannot be NULL). Example: CREATE TABLE Student( Sid NUMBER (5) CONSTRAINT PK_Student PRIMARY KEY, Sname VARCHAR2 (30) NOT NULL, Saddr VARCHAR2 (30), Sdno NUMBER(3) NOT NULL, LisenceNo VARCHAR2(10) UNIQUE); 7 5. CHECK: Defines a discrete list of values that a column can have. Example: CREATE TABLE Student( Sid NUMBER (5) CONSTRAINT PK_Student PRIMARY KEY, Sname VARCHAR2 (30) NOT NULL, Saddr VARCHAR2 (30), Sdno NUMBER(4) NOT NULL CONSTRAINT CK_Sdno CHECK (Sdno BETWEEN 0 AND 700), LisenceNo VARCHAR2(10) UNIQUE); 6. F OREIGN KEY : Implements referential integrity which constraints the values of a column to the current values that exist in another column in the same or different table. Example: CREATE TABLE Student( Sid NUMBER (5) CONSTRAINT PK_Student PRIMARY KEY, - - Sdno NUMBER(4) NOT NULL CONSTRAINT CK_Sdno CHECK (Sdno BETWEEN 0 AND 700) CONSTRAINT FOREIGN KEY(Sdno) REFERENCES Department(Dno), LisenceNo VARCHAR2(10) UNIQUE); 8 (a) Parent Table: Department Child Table: Student (b) Child Table insert restrict Child Table update restrict Parent Table update restrict Parent Table delete restrict Parent Table insert and Child Table delete not restricted. (c) NOT NULL in the foreign key enforces that the student must have a department tuple in the Department table. (d) Delete Cascade: i. version1: no parent delete when there is a child. Example on previous page. ii. version2: parent delete as well as all its children delete recursively. 9 Example of version2: CREATE TABLE Student( Sid NUMBER (5) CONSTRAINT PK_Student PRIMARY KEY, Sname VARCHAR2 (30) NOT NULL, - - - CONSTRAINT FK_Student_Sdno FOREIGN KEY (Sdno) REFERENCES Department(Dno) ON DELETE CASCADE); • All descendant rows at all levels are deleted when parent is deleted. • Lookup table should not have delete cascade because of many references to it. 10 Analyzing Constraints Through Data Dictionary 1. Each Oracle Database has a data dictionary with the following information. • Table definitions • Column names and data types • Sequences • View definitions • database links • Stored procedure • Other object descriptive information 2. Querying data dictionary information through views 3. View names: • U SER : Views of those objects created by the user. Example: U SER T ABLES, U SER T AB COLU M N S, U SER CON S COLU M N S, U SER CON ST RAIN T S, U SER T RIGGERS, U SER T RIGGERS COLS. 11 • ALL : Views of objects created by the user as well as others the user has access permission. • DBS : Views on all objects 12 Accessing Views on Data Dictionary 1. U SER T ABLES : This view has information about table names, tablespace names, etc. Example: select all table names for those tables that have been created in your current schema. SELECT TABLE_NAME FROM USER_TABLES 2. U SER T AB COLU M N S : This view contains information such as table names, column names, data types, etc. Example: Get table names for those tables with column like Sname. SELECT TABLE_NAME FROM USER_TAB_COLUMNS WHERE COLUMN_NAME LIKE ’%Sname%’ 13 Accessing Views on Constraints 1. U SER CON S COLU M N S : this view has columns such as owner of the table, constraint name, table name, column name, sequence position. View U SER CON S COLU M N S OWNER_TABLE TABLE_NAME COLUMN_NAME CONSTRAINT_NAME Admin Student Sid PK_Student Admin Student Sdno FK_Student_Sdno Admin Department Dno PK_Department Example: Get all constraint names for table Student on column Sdno. SELECT TABLE_NAME, COLUMN_NAME, CONSTRAINT_NAME FROM USER_CONS_COLUMNS WHERE TABLE_NAME="Student" AND COLUMN_NAME="Sdno" 2. U SER CON ST RAIN T S : This view has columns such as owner of the table, constraint name, constraint type (one of five), table name, search condition (for CHECK), delete cascade, owner of parent table, primary or unique key in the parent table. 14 R OW N ER:owner of the parent table. R stands for Relative. R CON ST RAIN T N AM E: name of Parent table PRIMARY KEY Constraint. View U SER CON ST RAIN T S OWNER Admin Admin Admin Admin CONSTRAINT_NAME PK_Student FK_Student_Sdno PK_Department CK_Sdno CONSTRAINT_TYPE ’P’ ’F’ ’P’ ’C’ TABLE_NAME Student Student Department Student SEARCH_CONDITION NULL NULL NULL Sdno BETWEEN 0 AND 700 R_OWNER NULL Admin NULL NULL R_CONSTRAINT_NAME NULL PK_Department NULL NULL DELETE_RULE NULL CASCADE NULL NULL Example: Get search conditions for all constraints on Student table. SELECT SEARCH_CONDITION FROM USER_CONSTRAINTS WHERE CONSTRAINT_NAME=’CK%’ AND TABLE_NAME=’Student’ 15 Example: Given a table name, get it’s foreign key constraint name, parent table and it’s primary key constraint name. SELECT A.CONSTRAINT_NAME Foreign_Key B.TABLE_NAME Parent_Table A.R_CONSTRAINT_NAME Parent_key A.DELETE_RULE Delete_Rule FROM USER_CONSTRAINTS A, USER_CONSTRAINTS B WHERE A.TABLE_NAME="Student" AND A.R_CONSTRAINT_NAME=B.CONSTRAINT_NAME Result: Foreign_key Parent_Table Parent_key Delete_Rule FK_Student_Sdno Department PK_Department CASCADE Example: Given a table name get all it’s foreign keys, parent table names and their primary keys, and apply this recursively using delete cascade (useful, say to find out which triggers will affect a table). This will require both SQL and stored programming. 16