1. Views and Constraints in SQL
1
Fall 2001 Database Systems 1
Views
• Views are virtual tables.
– their schema is defined with respect to attributes from other
tables.
– the tuples in a view are derived from base tables using select
statements.
CREATE VIEW itemswithbid (Name, Amount, Date, Buyer)
AS SELECT I.Name, B.Amount, B.Date, Buy.Name
FROM Items I, Bids B, Buyers Buy
WHERE (I.Iid = B.Iid) AND (B.Buyid = Buy.buyid)
Fall 2001 Database Systems 2
Views
• When views are created, their definition is placed in the data
dictionary.
• Views are treated as tables in Select queries.
SELECT I.name, AVG(I.amount)
FROM itemswithbid I
WHERE NOT EXISTS (
SELECT *
FROM itemswithbid I2
WHERE (I.name = I2.name) AND
(I.amount < 25)
GROUP BY I.name
• Views are replaced by their definition from the data dictionary at
query optimization time.
• A query against a view is valid if the view definition can be
expanded to a regular SQL query.
2. Views and Constraints in SQL
2
Fall 2001 Database Systems 3
Views with check option
• Views can be used to insert tuples into the relations they are
derived from.
CREATE VIEW smallbids
AS SELECT * FROM bids
WHERE bids.amount < 20
WITH CHECK OPTION
• The check option is optional and specifies that every row that is
inserted or updated through the view must conform to the definition
of the view.
• Any tuple in the base table that would not be visible through the
view after insert/update cannot be inserted/changed by this view.
• the following update may not work for some tuples:
UPDATE smallbids
SET amount = amount + 10
Fall 2001 Database Systems 4
Updatable views (single table)
1. If a view is defined by a query that contains SET or DISTINCT
operators, a GROUP BY clause, or a group function, then rows
cannot be inserted into, updated in, or deleted from the base
tables using the view.
2. If a view is defined with WITH CHECK OPTION, then a row cannot
be inserted into, or updated in, the base table (using the view), if
the view cannot select the row from the base table.
3. If a NOT NULL column that does not have a DEFAULT clause is
omitted from the view, then a row cannot be inserted into the base
table using the view.
4. If the view was created by using an expression, such as
DECODE(deptno, 10, "SALES", ...), then rows cannot be inserted
into or updated in the base table using the view.
3. Views and Constraints in SQL
3
Fall 2001 Database Systems 5
Updatable views (join table)
A modifiable join view is a view that contains more than one table in the
top-level FROM clause of the SELECT statement, and that does
not 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 pseudocolumn
A further restriction on which join views are modifiable is that if a view is
a join on other nested views, then the other nested views must be
mergeable into the top level view.
Finally, the joined tables should be key-preserving.
Fall 2001 Database Systems 6
Updateable views (key
preservation)
• Let V be a view involving relations R and S.
• The key for R (or S) is said to be preserved in V, if the
key for R is a key for V.
– Remember, no two tuples can have the same key value and
different values for other attributes
– After a join, the “key” property may be propagated to the new
attributes
– Even if the key for R is not in the view attributes, the key property
may still be maintained.
4. Views and Constraints in SQL
4
Fall 2001 Database Systems 7
Key preservation
CREATE 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 AS
SELECT e.Empno, e.Ename, e.Deptno,
e.Sal, d.Dname, d.Loc
FROM Emp_tab e, Dept_tab d
WHERE e.Deptno = d.Deptno AND
d.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 8
Views
• Value of views
– Views can be used as short cuts to
commonly asked complex queries.
– Views provide windows to the database,
allowing different users to view the same
data differently.
– Views make it possible to define security and
access control mechanisms at a finer
granularity than possible with tables.
5. Views and Constraints in SQL
5
Fall 2001 Database Systems 9
Views – side note
• Pseudo-columns are system variables that can
be 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 the
tuple
– USER: the identifier of the current user accessing the
table (like the whois command in Unix)
Fall 2001 Database Systems 10
CREATE 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 REFERENCES
Owners(Oid)
) ;
INSERT INTO Owners VALUES(1,’Sibel
Adali’, ‘ADALIS’) ;
INSERT INTO Owners VALUES(2, ‘David
Spooner’, ‘SPOOND’) ;
CREATE VIEW ownItems AS
SELECT I.Iid, I.Iname
FROM Items I, Owner O
WHERE I.Oid = O.Oid AND
O.Ouser = USER ;
6. Views and Constraints in SQL
6
Fall 2001 Database Systems 11
DROP Command
• Any table/view can be removed from the database using
DROP TABLE/VIEW command.
• If a view is dropped, then its description is removed from
the database.
• If a table is dropped, then all the data it contains is also
removed.
• Dropping a table may invalidate the existing views on this
table.
Fall 2001 Database Systems 12
Key and Unique Constraints
• The primary key and the unique constraint specify a set of attributes
that 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 every
update/insert
– if an update/insert violates a constraint, it is rejected!
some systems will not check these constraints unless an index
exists
CREATE UNIQUE KEY INDEX studentid ON student(sid)
7. Views and Constraints in SQL
7
Fall 2001 Database Systems 13
Alternate forms
CREATE TABLE student
( sid INTEGER
PRIMARY KEY,
lastname VARCHAR(30),
firstname VARCHAR(30),
major CHAR(4)
DEFAULT ‘None’,
email CHAR(255) UNIQUE,
entrydate DATE
DEFAULT 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 14
Name all your contraints
CREATE 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. Views and Constraints in SQL
8
Fall 2001 Database Systems 15
Referential integrity
• A table T1 may reference the tuples in another table T2 using a foreign
key 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 primary
key value from T2(B) or the null value in A
CREATE 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 16
Maintaining referential integrity
• Suppose T1(A) references T2(B)
– insert tuple into T1 with non-null A -- if T2 has no tuple such that
T1(A) = T2(B), reject the insertion
– change value of A in tuple in T1 -- if T2 has no tuple such that
T1(A) = T2(B) for new value of A, reject the update
– delete tuple from T2 -- if a tuple in T1 references the deleted
tuple:
• 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. Views and Constraints in SQL
9
Fall 2001 Database Systems 17
Maintaining referential integrity
CREATE 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 NULL
ON UPDATE CASCADE,
FOREIGN KEY (course_number, dept_id)
REFERENCES course(course_number, dept_id)
ON UPDATE CASCADE
)
Fall 2001 Database Systems 18
Constraints on attribute values
• NOT NULL -- attribute may not have a null value for any tuple
• CHECK -- limit the values a specific attribute may have
CREATE 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 INTEGER
CHECK ((totalcredits > 0) AND (totalcredits < 200))
)
10. Views and Constraints in SQL
10
Fall 2001 Database Systems 19
Check constraint
• If a check constraint involves a comparison with other relations, then
a select statement is needed
• Check is only checked when a tuple is inserted/updated
• Example: Instructors in the section relation must be from the Troy
campus
CREATE TABLE section (
…
instructor_id INTEGER
CHECK (instructor_id IN
(SELECT id FROM instructor, department
WHERE (instructor.dept_id = department.dept_id) AND
(department.address LIKE ‘*Troy*’) ))
)
Fall 2001 Database Systems 20
Using Domains
• It is possible to create your own domains and use them
in creating tables
CREATE 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. Views and Constraints in SQL
11
Fall 2001 Database Systems 21
General tuple-based constraints
• Check can be used for constraints on multiple
attributes in a relation
• Example: A section must have either a non-
null department id or instructor id at all times
CREATE TABLE section (
…
CHECK (instructor_id NOT NULL OR
section_number NOT NULL)
)
Fall 2001 Database Systems 22
Exercises
• Create the following constraints:
1. section -- the semester has to be fall or spring, and years
can be only between 1980 and 1999
2. student -- the gpa of a a student cannot fall below 0.0 and
cannot go above 4.0
semester 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. Views and Constraints in SQL
12
Fall 2001 Database Systems 23
lastname VARCHAR(30)
CHECK (length(lastname) > 4 AND
(lastname LIKE ‘%a%’ OR lastname LIKE ‘%e%’ OR
lastname LIKE ‘%i%’ OR lastname LIKE ‘%o%’ OR
lastname LIKE ‘%u%’ ) )
Exercises
3. 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 than
five letters and their last names should contain some vowels.
grade CHAR(1) CHECK (grade in (‘A’,’B’,’C’,’D’,’F’))
Fall 2001 Database Systems 24
Assertions
• Assertions are more general forms of constraints that
apply to tuples, sets of tables and a database in general.
CREATE ASSERTION assertion_name
CHECK where_clause
• Example: The total number of students in the ‘CS’ major
cannot exceed 400!
CREATE ASSERTION limitcs
CHECK (400 >= (SELECT count(*) FROM student
WHERE major = ‘CS’) );
Anything you would put in a
where clause goes in here
13. Views and Constraints in SQL
13
Fall 2001 Database Systems 25
Assertions
• No student can take two different sections of
the same course in the same semester!
CREATE ASSERTION no2sections
CHECK (NOT EXISTS (
SELECT t.sid, s.semester,
s.course_number, s.dept_id
FROM section s, transcript t
WHERE s.section_id = t.section_id
GROUP BY t.sid, s.semester,
s.course_number, s.dept_id
HAVING count(s.section_number) > 1)) ;
Fall 2001 Database Systems 26
Assertions
• If a students GPA is greater then 2.0, then she/he cannot be
on probation.
CREATE ASSERTION onprobation
CHECK (NOT EXISTS (
SELECT * FROM student
WHERE student.gpa > 2.0 AND
probation_date NOT NULL)) ;
Equivalent to:
CREATE TABLE student (
…
CHECK (student.gpa < 2.0 or probation_date NULL)
)
15. Views and Constraints in SQL
15
Fall 2001 Database Systems 29
Database for Exercises
student(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 30
Exercises
Write the following assertion for this database:
1. A student’s major is either “NONE” or one of the
department abbreviations.
CREATE ASSERTION a1
CHECK (NOT EXISTS (
SELECT * FROM student
WHERE (student.major ‘NONE’) AND
(student.major NOT IN
(SELECT abbreviation FROM department)))) ;
16. Views and Constraints in SQL
16
Fall 2001 Database Systems 31
Exercises
Write the following assertion for this database:
2. The total number of requirements for a major cannot
exceed 16 courses.
CREATE ASSERTION a2 CHECK
(NOT EXISTS (
SELECT major FROM requirement
GROUP BY major
HAVING count(*) 16 )) ;
Fall 2001 Database Systems 32
Exercises
Write the following assertion for this database:
3. The salary of an instructor cannot be greater than that of
another instructor in the same department with higher rank
(assume rank is an integer, high rank means high number)
CREATE ASSERTION a3
CHECK (NOT EXISTS (
SELECT * FROM instructor I
WHERE EXISTS (
SELECT * FROM instructor I2
WHERE I1.dept_id = I2.dept_id AND
I1.rank I2.rank AND
I1.salary I2.salary ))
17. Views and Constraints in SQL
17
Fall 2001 Database Systems 33
Exercises
Write the following assertion for this database:
4. The total number of credits for a student (in the student
table) is equal to the total number of credits in the
transcript.
CREATE ASSERTION a4
CHECK (NOT EXISTS (
SELECT * FROM student S
WHERE S.totalcredits
(SELECT sum(T.credits)
FROM transcript T
WHERE T.sid = S.sid)))
What if the student took the same course twice?
Fall 2001 Database Systems 34
Exercise 4 Correct Solution
• We will use the grade for the last section of any course the student
took (highest section id).
CREATE ASSERTION a4
CHECK (NOT EXISTS (
SELECT * FROM student S
WHERE S.totalcredits
(SELECT sum(T1.credits)
FROM transcript T1, section Sc1
WHERE (T1.sid = S.sid) AND
(Sc1.section_id = T1.section_id) AND NOT EXISTS
(SELECT * FROM transcript T2, section Sc2
WHERE (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) ) ) ) )