SlideShare une entreprise Scribd logo
1  sur  17
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.
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.
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.
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.
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 ;
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)
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)
)
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
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))
)
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
)
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))
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
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)
)
Views and Constraints in SQL
14
Fall 2001 Database Systems 27
Adding/removing constraints
• Naming constraints
gpa number(5,2) CONSTRAINT validgpa
CHECK ((gpa >= 1.0) AND (gpa <= 4.0))
CREATE DOMAIN gpadomain NUMBER(5,2)
CONSTRAINT validgpa
CHECK ((gpa >= 1.0) AND (gpa <= 4.0))
• Adding/dropping constraints
ALTER TABLE transcript ADD CONSTRAINT validcredits
CHECK (credits > 1 AND credits < 4)
ALTER TABLE transcript DROP CONSTRAINT validcredits
DROP ASSERTION onprobation
Fall 2001 Database Systems 28
Comparison of constraints
 ¢¡¤£¦¥¨§¦©
 §¦! 
$# ¥!%¥
 ¥ (' (¥ 
$# ¥(
  ¦ )012¥ 
Attribute-
based
CHECK
With attribute
On insertion to
relation or
attribute update
Tuple-
based
CHECK
Element of a
relation
schema
On insertion to
relation or tuple
update
Assertion
Element of
database
schema
On change to
any mentioned
relation
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)))) ;
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 ))
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) ) ) ) )

Contenu connexe

Tendances (19)

ADBMS Unit-II c
ADBMS Unit-II cADBMS Unit-II c
ADBMS Unit-II c
 
Query
QueryQuery
Query
 
Les13
Les13Les13
Les13
 
Modern SQL in Open Source and Commercial Databases
Modern SQL in Open Source and Commercial DatabasesModern SQL in Open Source and Commercial Databases
Modern SQL in Open Source and Commercial Databases
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
 
SQL Sort Notes
SQL Sort NotesSQL Sort Notes
SQL Sort Notes
 
SQL Tutorial for BCA-2
SQL Tutorial for BCA-2SQL Tutorial for BCA-2
SQL Tutorial for BCA-2
 
Designing and Creating Views, Inline Functions, and Synonyms
 Designing and Creating Views, Inline Functions, and Synonyms Designing and Creating Views, Inline Functions, and Synonyms
Designing and Creating Views, Inline Functions, and Synonyms
 
Lab2 ddl commands
Lab2 ddl commandsLab2 ddl commands
Lab2 ddl commands
 
Les02
Les02Les02
Les02
 
Les14
Les14Les14
Les14
 
Standard SQL features where PostgreSQL beats its competitors
Standard SQL features where PostgreSQL beats its competitorsStandard SQL features where PostgreSQL beats its competitors
Standard SQL features where PostgreSQL beats its competitors
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Sql
SqlSql
Sql
 
Adbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queriesAdbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queries
 
Oracle: DDL
Oracle: DDLOracle: DDL
Oracle: DDL
 
Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)
 
Oracle sql material
Oracle sql materialOracle sql material
Oracle sql material
 
Ddl commands
Ddl commandsDdl commands
Ddl commands
 

En vedette

[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms12
[Www.pkbulk.blogspot.com]dbms12[Www.pkbulk.blogspot.com]dbms12
[Www.pkbulk.blogspot.com]dbms12AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms03
[Www.pkbulk.blogspot.com]dbms03[Www.pkbulk.blogspot.com]dbms03
[Www.pkbulk.blogspot.com]dbms03AnusAhmad
 

En vedette (7)

[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05
 
[Www.pkbulk.blogspot.com]dbms12
[Www.pkbulk.blogspot.com]dbms12[Www.pkbulk.blogspot.com]dbms12
[Www.pkbulk.blogspot.com]dbms12
 
[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02
 
[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13
 
[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11
 
[Www.pkbulk.blogspot.com]dbms03
[Www.pkbulk.blogspot.com]dbms03[Www.pkbulk.blogspot.com]dbms03
[Www.pkbulk.blogspot.com]dbms03
 
Presentación1
Presentación1Presentación1
Presentación1
 

Similaire à [Www.pkbulk.blogspot.com]dbms10

Similaire à [Www.pkbulk.blogspot.com]dbms10 (20)

Physical Design and Development
Physical Design and DevelopmentPhysical Design and Development
Physical Design and Development
 
Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1
 
Sql server T-sql basics ppt-3
Sql server T-sql basics  ppt-3Sql server T-sql basics  ppt-3
Sql server T-sql basics ppt-3
 
DDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using OracleDDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using Oracle
 
Les10 Creating And Managing Tables
Les10 Creating And Managing TablesLes10 Creating And Managing Tables
Les10 Creating And Managing Tables
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
 
Introduction to Oracle Database.pptx
Introduction to Oracle Database.pptxIntroduction to Oracle Database.pptx
Introduction to Oracle Database.pptx
 
Revision sql te it new syllabus
Revision sql te it new syllabusRevision sql te it new syllabus
Revision sql te it new syllabus
 
Chap 7
Chap 7Chap 7
Chap 7
 
Steps towards of sql server developer
Steps towards of sql server developerSteps towards of sql server developer
Steps towards of sql server developer
 
Les10.ppt
Les10.pptLes10.ppt
Les10.ppt
 
05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptx05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptx
 
mySQL and Relational Databases
mySQL and Relational DatabasesmySQL and Relational Databases
mySQL and Relational Databases
 
BIS06 Physical Database Models
BIS06 Physical Database ModelsBIS06 Physical Database Models
BIS06 Physical Database Models
 
BIS06 Physical Database Models
BIS06 Physical Database ModelsBIS06 Physical Database Models
BIS06 Physical Database Models
 
Sql basics
Sql basicsSql basics
Sql basics
 
Sql commands
Sql commandsSql commands
Sql commands
 
chap 7.ppt(sql).ppt
chap 7.ppt(sql).pptchap 7.ppt(sql).ppt
chap 7.ppt(sql).ppt
 
3. ddl create
3. ddl create3. ddl create
3. ddl create
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
 

Plus de AnusAhmad

[Www.pkbulk.blogspot.com]file and indexing
[Www.pkbulk.blogspot.com]file and indexing[Www.pkbulk.blogspot.com]file and indexing
[Www.pkbulk.blogspot.com]file and indexingAnusAhmad
 
[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01AnusAhmad
 
9. java server faces
9. java server faces9. java server faces
9. java server facesAnusAhmad
 
8. java script
8. java script8. java script
8. java scriptAnusAhmad
 
2. http, html
2. http, html2. http, html
2. http, htmlAnusAhmad
 
6. hibernate
6. hibernate6. hibernate
6. hibernateAnusAhmad
 

Plus de AnusAhmad (15)

[Www.pkbulk.blogspot.com]file and indexing
[Www.pkbulk.blogspot.com]file and indexing[Www.pkbulk.blogspot.com]file and indexing
[Www.pkbulk.blogspot.com]file and indexing
 
[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09
 
[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07
 
[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06
 
[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04
 
[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01
 
9. java server faces
9. java server faces9. java server faces
9. java server faces
 
8. java script
8. java script8. java script
8. java script
 
7. struts
7. struts7. struts
7. struts
 
5. servlets
5. servlets5. servlets
5. servlets
 
4. jsp
4. jsp4. jsp
4. jsp
 
3. applets
3. applets3. applets
3. applets
 
2. http, html
2. http, html2. http, html
2. http, html
 
1. intro
1. intro1. intro
1. intro
 
6. hibernate
6. hibernate6. hibernate
6. hibernate
 

Dernier

Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 

Dernier (20)

Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 

[Www.pkbulk.blogspot.com]dbms10

  • 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) )
  • 14. Views and Constraints in SQL 14 Fall 2001 Database Systems 27 Adding/removing constraints • Naming constraints gpa number(5,2) CONSTRAINT validgpa CHECK ((gpa >= 1.0) AND (gpa <= 4.0)) CREATE DOMAIN gpadomain NUMBER(5,2) CONSTRAINT validgpa CHECK ((gpa >= 1.0) AND (gpa <= 4.0)) • Adding/dropping constraints ALTER TABLE transcript ADD CONSTRAINT validcredits CHECK (credits > 1 AND credits < 4) ALTER TABLE transcript DROP CONSTRAINT validcredits DROP ASSERTION onprobation Fall 2001 Database Systems 28 Comparison of constraints  ¢¡¤£¦¥¨§¦© §¦! $# ¥!%¥ ¥ (' (¥ $# ¥( ¦ )012¥ Attribute- based CHECK With attribute On insertion to relation or attribute update Tuple- based CHECK Element of a relation schema On insertion to relation or tuple update Assertion Element of database schema On change to any mentioned relation
  • 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) ) ) ) )