SlideShare a Scribd company logo
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) ) ) ) )
Ad

More Related Content

What's hot (19)

ADBMS Unit-II c
ADBMS Unit-II cADBMS Unit-II c
ADBMS Unit-II c
SSN College of Engineering, Kalavakkam
 
Query
QueryQuery
Query
Raj Devaraj
 
Les13
Les13Les13
Les13
arnold 7490
 
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
Markus Winand
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
Ashwin Dinoriya
 
SQL Sort Notes
SQL Sort NotesSQL Sort Notes
SQL Sort Notes
ShivaAdasule
 
SQL Tutorial for BCA-2
SQL Tutorial for BCA-2SQL Tutorial for BCA-2
SQL Tutorial for BCA-2
Raj vardhan
 
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
Tayba Farooqui
 
Lab2 ddl commands
Lab2 ddl commandsLab2 ddl commands
Lab2 ddl commands
Balqees Al.Mubarak
 
Les02
Les02Les02
Les02
Sudharsan S
 
Les14
Les14Les14
Les14
arnold 7490
 
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
Markus Winand
 
SQL Views
SQL ViewsSQL Views
SQL Views
baabtra.com - No. 1 supplier of quality freshers
 
Sql
SqlSql
Sql
jyothislides
 
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
Vaibhav Khanna
 
Oracle: DDL
Oracle: DDLOracle: DDL
Oracle: DDL
DataminingTools Inc
 
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)
Vidyasagar Mundroy
 
Oracle sql material
Oracle sql materialOracle sql material
Oracle sql material
prathap kumar
 
Ddl commands
Ddl commandsDdl commands
Ddl commands
Vasudeva Rao
 

Viewers also liked (7)

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

Similar to [Www.pkbulk.blogspot.com]dbms10 (20)

Physical Design and Development
Physical Design and DevelopmentPhysical Design and Development
Physical Design and Development
Er. Nawaraj Bhandari
 
Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1
sagaroceanic11
 
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
Vibrant Technologies & Computers
 
DDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using OracleDDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using Oracle
Farhan Aslam
 
askndmf,dskmlf,bvdmk,v nmdsvjkmc,dvjkcmsdcvjnkmd
askndmf,dskmlf,bvdmk,v nmdsvjkmc,dvjkcmsdcvjnkmdaskndmf,dskmlf,bvdmk,v nmdsvjkmc,dvjkcmsdcvjnkmd
askndmf,dskmlf,bvdmk,v nmdsvjkmc,dvjkcmsdcvjnkmd
talhahakeem295
 
SQL: Data Definition Language(DDL) command
SQL: Data Definition Language(DDL) commandSQL: Data Definition Language(DDL) command
SQL: Data Definition Language(DDL) command
sonali sonavane
 
Les10 Creating And Managing Tables
Les10 Creating And Managing TablesLes10 Creating And Managing Tables
Les10 Creating And Managing Tables
NETsolutions Asia: NSA – Thailand, Sripatum University: SPU
 
SQL _UNIT_DBMS_PRESENTSTATION_SQL _UNIT_DBMS_PRESENTSTATION
SQL _UNIT_DBMS_PRESENTSTATION_SQL _UNIT_DBMS_PRESENTSTATIONSQL _UNIT_DBMS_PRESENTSTATION_SQL _UNIT_DBMS_PRESENTSTATION
SQL _UNIT_DBMS_PRESENTSTATION_SQL _UNIT_DBMS_PRESENTSTATION
deeptanshudas100
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
YitbarekMurche
 
Introduction to Oracle Database.pptx
Introduction to Oracle Database.pptxIntroduction to Oracle Database.pptx
Introduction to Oracle Database.pptx
SiddhantBhardwaj26
 
Revision sql te it new syllabus
Revision sql te it new syllabusRevision sql te it new syllabus
Revision sql te it new syllabus
saurabhshertukde
 
Chap 7
Chap 7Chap 7
Chap 7
Karan Patil
 
Steps towards of sql server developer
Steps towards of sql server developerSteps towards of sql server developer
Steps towards of sql server developer
Ahsan Kabir
 
Les10.ppt
Les10.pptLes10.ppt
Les10.ppt
AlhassanFederated
 
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
MohamedNowfeek1
 
mySQL and Relational Databases
mySQL and Relational DatabasesmySQL and Relational Databases
mySQL and Relational Databases
webhostingguy
 
BIS06 Physical Database Models
BIS06 Physical Database ModelsBIS06 Physical Database Models
BIS06 Physical Database Models
Prithwis Mukerjee
 
BIS06 Physical Database Models
BIS06 Physical Database ModelsBIS06 Physical Database Models
BIS06 Physical Database Models
Prithwis Mukerjee
 
Sql basics
Sql basicsSql basics
Sql basics
Aman Lalpuria
 
Sql commands
Sql commandsSql commands
Sql commands
Pooja Dixit
 
Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1
sagaroceanic11
 
DDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using OracleDDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using Oracle
Farhan Aslam
 
askndmf,dskmlf,bvdmk,v nmdsvjkmc,dvjkcmsdcvjnkmd
askndmf,dskmlf,bvdmk,v nmdsvjkmc,dvjkcmsdcvjnkmdaskndmf,dskmlf,bvdmk,v nmdsvjkmc,dvjkcmsdcvjnkmd
askndmf,dskmlf,bvdmk,v nmdsvjkmc,dvjkcmsdcvjnkmd
talhahakeem295
 
SQL: Data Definition Language(DDL) command
SQL: Data Definition Language(DDL) commandSQL: Data Definition Language(DDL) command
SQL: Data Definition Language(DDL) command
sonali sonavane
 
SQL _UNIT_DBMS_PRESENTSTATION_SQL _UNIT_DBMS_PRESENTSTATION
SQL _UNIT_DBMS_PRESENTSTATION_SQL _UNIT_DBMS_PRESENTSTATIONSQL _UNIT_DBMS_PRESENTSTATION_SQL _UNIT_DBMS_PRESENTSTATION
SQL _UNIT_DBMS_PRESENTSTATION_SQL _UNIT_DBMS_PRESENTSTATION
deeptanshudas100
 
Introduction to Oracle Database.pptx
Introduction to Oracle Database.pptxIntroduction to Oracle Database.pptx
Introduction to Oracle Database.pptx
SiddhantBhardwaj26
 
Revision sql te it new syllabus
Revision sql te it new syllabusRevision sql te it new syllabus
Revision sql te it new syllabus
saurabhshertukde
 
Steps towards of sql server developer
Steps towards of sql server developerSteps towards of sql server developer
Steps towards of sql server developer
Ahsan Kabir
 
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
MohamedNowfeek1
 
mySQL and Relational Databases
mySQL and Relational DatabasesmySQL and Relational Databases
mySQL and Relational Databases
webhostingguy
 
BIS06 Physical Database Models
BIS06 Physical Database ModelsBIS06 Physical Database Models
BIS06 Physical Database Models
Prithwis Mukerjee
 
BIS06 Physical Database Models
BIS06 Physical Database ModelsBIS06 Physical Database Models
BIS06 Physical Database Models
Prithwis Mukerjee
 
Ad

More from 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
AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09
AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07
AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06
AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04
AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01
AnusAhmad
 
9. java server faces
9. java server faces9. java server faces
9. java server faces
AnusAhmad
 
8. java script
8. java script8. java script
8. java script
AnusAhmad
 
7. struts
7. struts7. struts
7. struts
AnusAhmad
 
5. servlets
5. servlets5. servlets
5. servlets
AnusAhmad
 
4. jsp
4. jsp4. jsp
4. jsp
AnusAhmad
 
3. applets
3. applets3. applets
3. applets
AnusAhmad
 
2. http, html
2. http, html2. http, html
2. http, html
AnusAhmad
 
1. intro
1. intro1. intro
1. intro
AnusAhmad
 
6. hibernate
6. hibernate6. hibernate
6. hibernate
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 indexing
AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09
AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07
AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06
AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04
AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01
AnusAhmad
 
9. java server faces
9. java server faces9. java server faces
9. java server faces
AnusAhmad
 
8. java script
8. java script8. java script
8. java script
AnusAhmad
 
2. http, html
2. http, html2. http, html
2. http, html
AnusAhmad
 
6. hibernate
6. hibernate6. hibernate
6. hibernate
AnusAhmad
 

Recently uploaded (20)

LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 

[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) ) ) ) )