Published on

Introduction to database lecture# 10: This lecture is all about SQL Views and Constraints and more...

Published in: Education, Technology
1 Comment
  • Nice post very helpful

    Are you sure you want to  Yes  No
    Your message goes here
  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. Views and Constraints in SQL1Fall 2001 Database Systems 1Views• Views are virtual tables.– their schema is defined with respect to attributes from othertables.– the tuples in a view are derived from base tables using selectstatements.CREATE VIEW itemswithbid (Name, Amount, Date, Buyer)AS SELECT I.Name, B.Amount, B.Date, Buy.NameFROM Items I, Bids B, Buyers BuyWHERE (I.Iid = B.Iid) AND (B.Buyid = Buy.buyid)Fall 2001 Database Systems 2Views• When views are created, their definition is placed in the datadictionary.• Views are treated as tables in Select queries.SELECT I.name, AVG(I.amount)FROM itemswithbid IWHERE NOT EXISTS (SELECT *FROM itemswithbid I2WHERE (I.name = I2.name) AND(I.amount < 25)GROUP BY I.name• Views are replaced by their definition from the data dictionary atquery optimization time.• A query against a view is valid if the view definition can beexpanded to a regular SQL query.
  2. 2. Views and Constraints in SQL2Fall 2001 Database Systems 3Views with check option• Views can be used to insert tuples into the relations they arederived from.CREATE VIEW smallbidsAS SELECT * FROM bidsWHERE bids.amount < 20WITH CHECK OPTION• The check option is optional and specifies that every row that isinserted or updated through the view must conform to the definitionof the view.• Any tuple in the base table that would not be visible through theview after insert/update cannot be inserted/changed by this view.• the following update may not work for some tuples:UPDATE smallbidsSET amount = amount + 10Fall 2001 Database Systems 4Updatable views (single table)1. If a view is defined by a query that contains SET or DISTINCToperators, a GROUP BY clause, or a group function, then rowscannot be inserted into, updated in, or deleted from the basetables using the view.2. If a view is defined with WITH CHECK OPTION, then a row cannotbe inserted into, or updated in, the base table (using the view), ifthe view cannot select the row from the base table.3. If a NOT NULL column that does not have a DEFAULT clause isomitted from the view, then a row cannot be inserted into the basetable using the view.4. If the view was created by using an expression, such asDECODE(deptno, 10, "SALES", ...), then rows cannot be insertedinto or updated in the base table using the view.
  3. 3. Views and Constraints in SQL3Fall 2001 Database Systems 5Updatable views (join table)A modifiable join view is a view that contains more than one table in thetop-level FROM clause of the SELECT statement, and that doesnot contain any of the following:• DISTINCT operator• Aggregate functions: AVG, COUNT, GLB, MAX, MIN, STDDEV,SUM, or VARIANCE• Set operations: UNION, UNION ALL, INTERSECT, MINUS• GROUP BY or HAVING clauses• START WITH or CONNECT BY clauses• ROWNUM pseudocolumnA further restriction on which join views are modifiable is that if a view isa join on other nested views, then the other nested views must bemergeable into the top level view.Finally, the joined tables should be key-preserving.Fall 2001 Database Systems 6Updateable views (keypreservation)• Let V be a view involving relations R and S.• The key for R (or S) is said to be preserved in V, if thekey for R is a key for V.– Remember, no two tuples can have the same key value anddifferent values for other attributes– After a join, the “key” property may be propagated to the newattributes– Even if the key for R is not in the view attributes, the key propertymay still be maintained.
  4. 4. Views and Constraints in SQL4Fall 2001 Database Systems 7Key preservationCREATE TABLE Dept_tab (Deptno NUMBER(4) PRIMARY KEY,Dname VARCHAR2(14),Loc VARCHAR2(13));CREATE TABLE Emp_tab (Empno NUMBER(4) PRIMARY KEY,Ename VARCHAR2(10),Job varchar2(9),Mgr NUMBER(4),Hiredate DATE,Sal NUMBER(7,2),Comm NUMBER(7,2),Deptno NUMBER(2),FOREIGN KEY (Deptno)REFERENCES Dept_tab(Deptno));CREATE VIEW Emp_dept_view ASSELECT e.Empno, e.Ename, e.Deptno,e.Sal, d.Dname, d.LocFROM Emp_tab e, Dept_tab dWHERE e.Deptno = d.Deptno ANDd.Loc IN (DALLAS, NEW YORK,BOSTON);Is the key for relation Emp_tab preserved?Is the key for relation Dept_tab preserved?Fall 2001 Database Systems 8Views• Value of views– Views can be used as short cuts tocommonly asked complex queries.– Views provide windows to the database,allowing different users to view the samedata differently.– Views make it possible to define security andaccess control mechanisms at a finergranularity than possible with tables.
  5. 5. Views and Constraints in SQL5Fall 2001 Database Systems 9Views – side note• Pseudo-columns are system variables that canbe queried as if they are actual columns• All tables have the same pseudo-columns,attached to every tuple in the table• Examples:– ROWID: the identifier of the physical location of thetuple– USER: the identifier of the current user accessing thetable (like the whois command in Unix)Fall 2001 Database Systems 10CREATE TABLE Owners (Oid INTEGER PRIMARY KEY,OName VARCHAR2(40),Ouser VARCHAR2(40)) ;CREATE TABLE items (Iid INTEGER PRIMARY KEY,IName VARCHAR2(40),Oid INT,FOREIGN KEY Oid REFERENCESOwners(Oid)) ;INSERT INTO Owners VALUES(1,’SibelAdali’, ‘ADALIS’) ;INSERT INTO Owners VALUES(2, ‘DavidSpooner’, ‘SPOOND’) ;CREATE VIEW ownItems ASSELECT I.Iid, I.InameFROM Items I, Owner OWHERE I.Oid = O.Oid ANDO.Ouser = USER ;
  6. 6. Views and Constraints in SQL6Fall 2001 Database Systems 11DROP Command• Any table/view can be removed from the database usingDROP TABLE/VIEW command.• If a view is dropped, then its description is removed fromthe database.• If a table is dropped, then all the data it contains is alsoremoved.• Dropping a table may invalidate the existing views on thistable.Fall 2001 Database Systems 12Key and Unique Constraints• The primary key and the unique constraint specify a set of attributesthat will be unique for all tuples– a table may have many unique constraints– a table may have at most one primary key– a foreign key can refer only to a primary key– primary key or unique constraints should be checked for everyupdate/insert– if an update/insert violates a constraint, it is rejected!some systems will not check these constraints unless an indexexistsCREATE UNIQUE KEY INDEX studentid ON student(sid)
  7. 7. Views and Constraints in SQL7Fall 2001 Database Systems 13Alternate formsCREATE TABLE student( sid INTEGERPRIMARY KEY,lastname VARCHAR(30),firstname VARCHAR(30),major CHAR(4)DEFAULT ‘None’,email CHAR(255) UNIQUE,entrydate DATEDEFAULT SYSDATE,gpa NUMBER(5,2),total_credits INTEGER,probation_date DATE,UNIQUE(lastname, firstname,major))CREATE TABLE course( course_number INTEGER,dept_id INTEGER,course_name VARCHAR(30),PRIMARY KEY(course_number,dept_id))Fall 2001 Database Systems 14Name all your contraintsCREATE TABLE student( sid INTEGER,lastname VARCHAR(30),firstname VARCHAR(30),major CHAR(4) DEFAULT ‘None’,email CHAR(255),entrydate DATE DEFAULT SYSDATE,gpa NUMBER(5,2),total_credits INTEGER,probation_date DATE,CONSTRAINT student_pk PRIMARY KEY (sid),CONSTRAINT unique_lfm UNIQUE(lastname, firstname, major)CONSTRAINT unique_email UNIQUE(email))
  8. 8. Views and Constraints in SQL8Fall 2001 Database Systems 15Referential integrity• A table T1 may reference the tuples in another table T2 using a foreignkey declaration– all attributes in T2’s primary key must be referenced in T1– if T1(A) references T2(B), then each tuple in T1 either has a primarykey value from T2(B) or the null value in ACREATE TABLE section (section_id INTEGER PRIMARY KEY,section_number INTEGER NOT NULL,course_number INTEGER NOT NULL,dept_id INTEGER,semester CHAR(8),instructor_id INTEGER REFERENCES instructor(id),FOREIGN KEY (course_number, dept_id)REFERENCES course(course_number, dept_id))Fall 2001 Database Systems 16Maintaining referential integrity• Suppose T1(A) references T2(B)– insert tuple into T1 with non-null A -- if T2 has no tuple such thatT1(A) = T2(B), reject the insertion– change value of A in tuple in T1 -- if T2 has no tuple such thatT1(A) = T2(B) for new value of A, reject the update– delete tuple from T2 -- if a tuple in T1 references the deletedtuple:• reject the delete (default action)• delete the tuple in T1 (known as a cascade delete)• set A in the T1 tuple to null (known as set null option)– change value of T2(B) in a tuple -- same as above
  9. 9. Views and Constraints in SQL9Fall 2001 Database Systems 17Maintaining referential integrityCREATE TABLE section (section_id INTEGER PRIMARY KEY,section_number INTEGER NOT NULL,course_number INTEGER NOT NULL,dept_id INTEGER,semester CHAR(10),instructor_id INTEGER ,FOREIGN KEY(instructor_id)REFERENCES instructor(id)ON DELETE SET NULLON UPDATE CASCADE,FOREIGN KEY (course_number, dept_id)REFERENCES course(course_number, dept_id)ON UPDATE CASCADE)Fall 2001 Database Systems 18Constraints on attribute values• NOT NULL -- attribute may not have a null value for any tuple• CHECK -- limit the values a specific attribute may haveCREATE TABLE section (…semester CHAR(10)CHECK ((semester like ‘Spring_’) or (semester like ‘Fall_’) or(semester like ‘Summer_I’) or (semester like ‘Summer_II’)))CREATE TABLE student (…gender CHAR(1)CHECK (gender IN (‘F’ , ‘M’)),totalcredits INTEGERCHECK ((totalcredits > 0) AND (totalcredits < 200)))
  10. 10. Views and Constraints in SQL10Fall 2001 Database Systems 19Check constraint• If a check constraint involves a comparison with other relations, thena select statement is needed• Check is only checked when a tuple is inserted/updated• Example: Instructors in the section relation must be from the TroycampusCREATE TABLE section (…instructor_id INTEGERCHECK (instructor_id IN(SELECT id FROM instructor, departmentWHERE (instructor.dept_id = department.dept_id) AND(department.address LIKE ‘*Troy*’) )))Fall 2001 Database Systems 20Using Domains• It is possible to create your own domains and use themin creating tablesCREATE DOMAIN SemesterD CHAR(10)CHECK ((VALUE like ‘Spring__’) or(VALUE like ‘Fall__’) or(VALUE like ‘Summer__I’) or(VALUE like ‘Summer__II’))CREATE TABLE section (…semester SemesterD)
  11. 11. Views and Constraints in SQL11Fall 2001 Database Systems 21General tuple-based constraints• Check can be used for constraints on multipleattributes in a relation• Example: A section must have either a non-null department id or instructor id at all timesCREATE TABLE section (…CHECK (instructor_id NOT NULL ORsection_number NOT NULL))Fall 2001 Database Systems 22Exercises• Create the following constraints:1. section -- the semester has to be fall or spring, and yearscan be only between 1980 and 19992. student -- the gpa of a a student cannot fall below 0.0 andcannot go above 4.0semester CHAR(10)CHECK ((semester=‘Fall’ OR semester=‘Spring’)AND year>1980 AND year<1999 )gpa number(5,2) CHECK ((gpa >= 0.0) AND (gpa <= 4.0))
  12. 12. Views and Constraints in SQL12Fall 2001 Database Systems 23lastname VARCHAR(30)CHECK (length(lastname) > 4 AND(lastname LIKE ‘%a%’ OR lastname LIKE ‘%e%’ ORlastname LIKE ‘%i%’ OR lastname LIKE ‘%o%’ ORlastname LIKE ‘%u%’ ) )Exercises3. student -- the grade in the transcript relation can only be one of‘A’,’B’,’C’,’D’ or ‘F’4. instructor -- instructors cannot have last names with less thanfive letters and their last names should contain some vowels.grade CHAR(1) CHECK (grade in (‘A’,’B’,’C’,’D’,’F’))Fall 2001 Database Systems 24Assertions• Assertions are more general forms of constraints thatapply to tuples, sets of tables and a database in general.CREATE ASSERTION assertion_nameCHECK where_clause• Example: The total number of students in the ‘CS’ majorcannot exceed 400!CREATE ASSERTION limitcsCHECK (400 >= (SELECT count(*) FROM studentWHERE major = ‘CS’) );Anything you would put in awhere clause goes in here
  13. 13. Views and Constraints in SQL13Fall 2001 Database Systems 25Assertions• No student can take two different sections ofthe same course in the same semester!CREATE ASSERTION no2sectionsCHECK (NOT EXISTS (SELECT t.sid, s.semester,s.course_number, s.dept_idFROM section s, transcript tWHERE s.section_id = t.section_idGROUP BY t.sid, s.semester,s.course_number, s.dept_idHAVING count(s.section_number) > 1)) ;Fall 2001 Database Systems 26Assertions• If a students GPA is greater then 2.0, then she/he cannot beon probation.CREATE ASSERTION onprobationCHECK (NOT EXISTS (SELECT * FROM studentWHERE student.gpa > 2.0 ANDprobation_date NOT NULL)) ;Equivalent to:CREATE TABLE student (…CHECK (student.gpa < 2.0 or probation_date NULL))
  14. 14. Views and Constraints in SQL14Fall 2001 Database Systems 27Adding/removing constraints• Naming constraintsgpa number(5,2) CONSTRAINT validgpaCHECK ((gpa >= 1.0) AND (gpa <= 4.0))CREATE DOMAIN gpadomain NUMBER(5,2)CONSTRAINT validgpaCHECK ((gpa >= 1.0) AND (gpa <= 4.0))• Adding/dropping constraintsALTER TABLE transcript ADD CONSTRAINT validcreditsCHECK (credits > 1 AND credits < 4)ALTER TABLE transcript DROP CONSTRAINT validcreditsDROP ASSERTION onprobationFall 2001 Database Systems 28Comparison of constraints ¢¡¤£¦¥¨§¦© §¦! $# ¥!%¥ ¥ ( (¥ $# ¥( ¦ )012¥ Attribute-basedCHECKWith attributeOn insertion torelation orattribute updateTuple-basedCHECKElement of arelationschemaOn insertion torelation or tupleupdateAssertionElement ofdatabaseschemaOn change toany mentionedrelation
  15. 15. Views and Constraints in SQL15Fall 2001 Database Systems 29Database for Exercisesstudent(sid, lastname, firstname, major, entrydate, gpa,total_credits, probation_date)course(course_number, dept_id, course_name)department(dept_id, department_name, abbreviation,address)instructor(instructor_id, firstname, lastname, dept_id, rank,salary)section(section_id, section_number, course_number,dept_id, semester, instructor_id)transcript(sid, section_id, credits, grade)requirement(req_id, major, course_number, dept_id)Fall 2001 Database Systems 30ExercisesWrite the following assertion for this database:1. A student’s major is either “NONE” or one of thedepartment abbreviations.CREATE ASSERTION a1CHECK (NOT EXISTS (SELECT * FROM studentWHERE (student.major ‘NONE’) AND(student.major NOT IN(SELECT abbreviation FROM department)))) ;
  16. 16. Views and Constraints in SQL16Fall 2001 Database Systems 31ExercisesWrite the following assertion for this database:2. The total number of requirements for a major cannotexceed 16 courses.CREATE ASSERTION a2 CHECK(NOT EXISTS (SELECT major FROM requirementGROUP BY majorHAVING count(*) 16 )) ;Fall 2001 Database Systems 32ExercisesWrite the following assertion for this database:3. The salary of an instructor cannot be greater than that ofanother instructor in the same department with higher rank(assume rank is an integer, high rank means high number)CREATE ASSERTION a3CHECK (NOT EXISTS (SELECT * FROM instructor IWHERE EXISTS (SELECT * FROM instructor I2WHERE I1.dept_id = I2.dept_id ANDI1.rank I2.rank ANDI1.salary I2.salary ))
  17. 17. Views and Constraints in SQL17Fall 2001 Database Systems 33ExercisesWrite the following assertion for this database:4. The total number of credits for a student (in the studenttable) is equal to the total number of credits in thetranscript.CREATE ASSERTION a4CHECK (NOT EXISTS (SELECT * FROM student SWHERE S.totalcredits (SELECT sum(T.credits)FROM transcript TWHERE T.sid = S.sid)))What if the student took the same course twice?Fall 2001 Database Systems 34Exercise 4 Correct Solution• We will use the grade for the last section of any course the studenttook (highest section id).CREATE ASSERTION a4CHECK (NOT EXISTS (SELECT * FROM student SWHERE S.totalcredits (SELECT sum(T1.credits)FROM transcript T1, section Sc1WHERE (T1.sid = S.sid) AND(Sc1.section_id = T1.section_id) AND NOT EXISTS(SELECT * FROM transcript T2, section Sc2WHERE (Sc2.section_id = T2.section_id) AND(Sc1.course_number = Sc2.course_number) AND(Sc1.dept_id = Sc2.dept_id) AND(T2.sid = S.sid) AND(T1.section_id T2.section_id) ) ) ) )