0% found this document useful (0 votes)
10 views10 pages

CH 4

Uploaded by

phuongmaivu744
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views10 pages

CH 4

Uploaded by

phuongmaivu744
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Chapter 4: Intermediate SQL

 Join Expressions
 Views
 Transactions
 Integrity Constraints
 SQL Data Types and Schemas
Chapter 4 : Intermediate SQL  Index Definition in SQL
 Authorization

Database System Concepts, 7th Ed.


©Silberschatz, Korth and Sudarshan
See www.db-book.com for conditions on re-use

Database System Concepts - 7th Edition 4.2 ©Silberschatz, Korth and Sudarshan

Joined Relations Natural Join in SQL

 Join operations take two relations and return as a  Natural join matches tuples with the same values for all
result another relation. common attributes, and retains only one copy of each
common column.
 A join operation is a Cartesian product which requires
that tuples in the two relations match (under some  List the names of instructors along with the course ID of
the courses that they taught
condition). It also specifies the attributes that are
present in the result of the join • select name, course_id
from students, takes
 The join operations are typically used as subquery where student.ID = takes.ID;
expressions in the from clause
 Same query in SQL with “natural join” construct
 Three types of joins: • select name, course_id
• Natural join from student natural join takes;
• Inner join
• Outer join

Database System Concepts - 7th Edition 4.3 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.4 ©Silberschatz, Korth and Sudarshan

Natural Join in SQL (Cont.) Student Relation

 The from clause in can have multiple relations combined


using natural join:
select A1, A2, … An
from r1 natural join r2 natural join .. natural join rn
where P ;

Database System Concepts - 7th Edition 4.5 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.6 ©Silberschatz, Korth and Sudarshan
Takes Relation student natural join takes

Database System Concepts - 7th Edition 4.7 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.8 ©Silberschatz, Korth and Sudarshan

Dangerous in Natural Join Outer Join


 Beware of unrelated attributes with same name which get  An extension of the join operation that avoids loss of
equated incorrectly information.
 Example -- List the names of students instructors along with  Computes the join and then adds tuples form one relation
the titles of courses that they have taken
that does not match tuples in the other relation to the result
• Correct version of the join.
select name, title  Uses null values.
from student natural join takes, course
where takes.course_id = course.course_id;  Three forms of outer join:
• Incorrect version • left outer join
select name, title • right outer join
from student natural join takes natural join course;
• full outer join
 This query omits all (student name, course title) pairs where
the student takes a course in a department other than the
student's own department.
 The correct version (above), correctly outputs such pairs.

Database System Concepts - 7th Edition 4.9 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.13 ©Silberschatz, Korth and Sudarshan

Outer Join Examples Left Outer Join

 Relation course  course natural left outer join prereq

 Relation prereq
 In relational algebra: course ⟕ prereq

 Observe that
course information is missing for CS-437
prereq information is missing for CS-315

Database System Concepts - 7th Edition 4.14 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.15 ©Silberschatz, Korth and Sudarshan
Right Outer Join Full Outer Join

 course natural right outer join prereq  course natural full outer join prereq

 In relational algebra: course ⟖ prereq  In relational algebra: course ⟗ prereq

Database System Concepts - 7th Edition 4.16 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.17 ©Silberschatz, Korth and Sudarshan

Joined Types and Conditions Joined Relations – Examples


 Join operations take two relations and return as a result  course natural right outer join prereq
another relation.
 These additional operations are typically used as subquery
expressions in the from clause
 Join condition – defines which tuples in the two relations
match, and what attributes are present in the result of the join.
 Join type – defines how tuples in each relation that do not  course full outer join prereq using (course_id)
match any tuple in the other relation (based on the join
condition) are treated.

Database System Concepts - 7th Edition 4.18 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.19 ©Silberschatz, Korth and Sudarshan

Joined Relations – Examples Joined Relations – Examples

 course inner join prereq on  course natural right outer join prereq
course.course_id = prereq.course_id

 What is the difference between the above, and a natural  course full outer join prereq using (course_id)
join?
 course left outer join prereq on
course.course_id = prereq.course_id

Database System Concepts - 7th Edition 4.20 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.21 ©Silberschatz, Korth and Sudarshan
Views View Definition
 In some cases, it is not desirable for all users to see the  A view is defined using the create view statement which
entire logical model (that is, all the actual relations stored in has the form
the database.)
create view v as < query expression >
 Consider a person who needs to know an instructors name
and department, but not the salary. This person should see a where <query expression> is any legal SQL expression.
relation described, in SQL, by The view name is represented by v.
 Once a view is defined, the view name can be used to refer
select ID, name, dept_name to the virtual relation that the view generates.
from instructor
 View definition is not the same as creating a new relation
by evaluating the query expression
 A view provides a mechanism to hide certain data from the • Rather, a view definition causes the saving of an
view of certain users. expression; the expression is substituted into queries
 Any relation that is not of the conceptual model but is made using the view.
visible to a user as a “virtual relation” is called a view.

Database System Concepts - 7th Edition 4.22 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.23 ©Silberschatz, Korth and Sudarshan

View Definition and Use Views Defined Using Other Views


 A view of instructors without their salary  One view may be used in the expression defining another
view
create view faculty as
 A view relation v1 is said to depend directly on a view
select ID, name, dept_name
relation v2 if v2 is used in the expression defining v1
from instructor
 A view relation v1 is said to depend on view relation v2 if
 Find all instructors in the Biology department
either v1 depends directly to v2 or there is a path of
select name dependencies from v1 to v2
from faculty  A view relation v is said to be recursive if it depends on
where dept_name = 'Biology' itself.
 Create a view of department salary totals
create view departments_total_salary(dept_name, total_salary) as
select dept_name, sum (salary)
from instructor
group by dept_name;

Database System Concepts - 7th Edition 4.24 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.25 ©Silberschatz, Korth and Sudarshan

Views Defined Using Other Views View Expansion


 create view physics_fall_2017 as  Expand the view :
select course.course_id, sec_id, building, room_number create view physics_fall_2017_watson as
from course, section select course_id, room_number
where course.course_id = section.course_id from physics_fall_2017
and course.dept_name = 'Physics' where building= 'Watson'
and section.semester = 'Fall'  To:
and section.year = '2017'; create view physics_fall_2017_watson as
select course_id, room_number
from (select course.course_id, building, room_number
 create view physics_fall_2017_watson as
from course, section
select course_id, room_number
where course.course_id = section.course_id
from physics_fall_2017
and course.dept_name = 'Physics'
where building= 'Watson';
and section.semester = 'Fall'
and section.year = '2017')
where building= 'Watson';

Database System Concepts - 7th Edition 4.26 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.27 ©Silberschatz, Korth and Sudarshan
View Expansion (Cont.) Materialized Views
 A way to define the meaning of views defined in terms of other  Certain database systems allow view relations to be
views. physically stored.
 Let view v1 be defined by an expression e1 that may itself • Physical copy created when the view is defined.
contain uses of view relations. • Such views are called Materialized view:
 View expansion of an expression repeats the following  If relations used in the query are updated, the
replacement step: materialized view result becomes out of date
repeat • Need to maintain the view, by updating the view
Find any view relation vi in e1 whenever the underlying relations are updated.
Replace the view relation vi by the expression defining vi
until no more view relations are present in e1
 As long as the view definitions are not recursive, this loop will
terminate

Database System Concepts - 7th Edition 4.28 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.29 ©Silberschatz, Korth and Sudarshan

Update of a View Some Updates Cannot be Translated Uniquely

 Add a new tuple to faculty view which we defined earlier


 create view instructor_info as
insert into faculty select ID, name, building
values ('30765', 'Green', 'Music'); from instructor, department
where instructor.dept_name= department.dept_name;
 This insertion must be represented by the insertion into the
instructor relation  insert into instructor_info
• Must have a value for salary. values ('69987', 'White', 'Taylor');
 Two approaches  Issues
• Reject the insert • Which department, if multiple departments in Taylor?
• Inset the tuple • What if no department is in Taylor?
('30765', 'Green', 'Music', null)
into the instructor relation

Database System Concepts - 7th Edition 4.30 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.31 ©Silberschatz, Korth and Sudarshan

And Some Not at All View Updates in SQL


 create view history_instructors as  Most SQL implementations allow updates only on simple
select *
views
from instructor
where dept_name= 'History'; • The from clause has only one database relation.
 What happens if we insert • The select clause contains only attribute names of the
relation, and does not have any expressions, aggregates,
('25566', 'Brown', 'Biology', 100000)
or distinct specification.
into history_instructors?
• Any attribute not listed in the select clause can be set to
null
• The query does not have a group by or having clause.

Database System Concepts - 7th Edition 4.32 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.33 ©Silberschatz, Korth and Sudarshan
Transactions Integrity Constraints
 A transaction consists of a sequence of query and/or update
 Integrity constraints guard against accidental damage
statements and is a “unit” of work
to the database, by ensuring that authorized changes
 The SQL standard specifies that a transaction begins implicitly to the database do not result in a loss of data
when an SQL statement is executed. consistency.
 The transaction must end with one of the following statements: • A checking account must have a balance greater
• Commit work. The updates performed by the transaction than $10,000.00
become permanent in the database.
• A salary of a bank employee must be at least
• Rollback work. All the updates performed by the SQL $4.00 an hour
statements in the transaction are undone.
• A customer must have a (non-null) phone number
 Atomic transaction
• either fully executed or rolled back as if it never occurred
 Isolation from concurrent transactions

Database System Concepts - 7th Edition 4.34 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.35 ©Silberschatz, Korth and Sudarshan

Constraints on a Single Relation Not Null Constraints

 not null  not null


 primary key • Declare name and budget to be not null
 unique name varchar(20) not null
budget numeric(12,2) not null
 check (P), where P is a predicate

Database System Concepts - 7th Edition 4.36 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.37 ©Silberschatz, Korth and Sudarshan

Unique Constraints The check clause

 unique ( A1, A2, …, Am)  The check (P) clause specifies a predicate P that must be
satisfied by every tuple in a relation.
• The unique specification states that the attributes
A1, A2, …, Am form a candidate key.  Example: ensure that semester is one of fall, winter, spring or
summer
• Candidate keys are permitted to be null (in contrast
to primary keys). create table section
(course_id varchar (8),
sec_id varchar (8),
semester varchar (6),
year numeric (4,0),
building varchar (15),
room_number varchar (7),
time slot id varchar (4),
primary key (course_id, sec_id, semester, year),
check (semester in ('Fall', 'Winter', 'Spring', 'Summer')))

Database System Concepts - 7th Edition 4.38 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.39 ©Silberschatz, Korth and Sudarshan
Referential Integrity Referential Integrity (Cont.)

 Ensures that a value that appears in one relation for a  Foreign keys can be specified as part of the SQL create
given set of attributes also appears for a certain set of table statement
attributes in another relation. foreign key (dept_name) references department
• Example: If “Biology” is a department name  By default, a foreign key references the primary-key
appearing in one of the tuples in the instructor attributes of the referenced table.
relation, then there exists a tuple in the
department relation for “Biology”.  SQL allows a list of attributes of the referenced relation to
be specified explicitly.
 Let A be a set of attributes. Let R and S be two
relations that contain attributes A and where A is the foreign key (dept_name) references department
primary key of S. A is said to be a foreign key of R if (dept_name)
for any values of A appearing in R these values also
appear in S.

Database System Concepts - 7th Edition 4.40 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.41 ©Silberschatz, Korth and Sudarshan

Cascading Actions in Referential Integrity Integrity Constraint Violation During Transactions

 When a referential-integrity constraint is violated, the normal  Consider:


procedure is to reject the action that caused the violation. create table person (
 An alternative, in case of delete or update is to cascade ID char(10),
name char(40),
create table course ( mother char(10),
(… father char(10),
dept_name varchar(20), primary key ID,
foreign key (dept_name) references department foreign key father references person,
on delete cascade foreign key mother references person)
on update cascade,  How to insert a tuple without causing constraint violation?
. . .) • Insert father and mother of a person before inserting person
 Instead of cascade we can use : • OR, set father and mother to null initially, update after
• set null, inserting all persons (not possible if father and mother
attributes declared to be not null)
• set default
• OR defer constraint checking

Database System Concepts - 7th Edition 4.42 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.43 ©Silberschatz, Korth and Sudarshan

Complex Check Conditions Assertions


 The predicate in the check clause can be an arbitrary predicate  An assertion is a predicate expressing a condition that we
that can include a subquery. wish the database always to satisfy.
check (time_slot_id in (select time_slot_id from time_slot))  The following constraints, can be expressed using assertions:
The check condition states that the time_slot_id in each tuple  For each tuple in the student relation, the value of the attribute
in the section relation is actually the identifier of a time slot in tot_cred must equal the sum of credits of courses that the
the time_slot relation. student has completed successfully.
• The condition has to be checked not only when a tuple is  An instructor cannot teach in two different classrooms in a
inserted or modified in section , but also when the relation semester in the same time slot
time_slot changes  An assertion in SQL takes the form:
create assertion <assertion-name> check (<predicate>);

Database System Concepts - 7th Edition 4.44 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.45 ©Silberschatz, Korth and Sudarshan
Built-in Data Types in SQL Large-Object Types
 date: Dates, containing a (4 digit) year, month and date  Large objects (photos, videos, CAD files, etc.) are stored as
• Example: date '2005-7-27' a large object:
 time: Time of day, in hours, minutes and seconds. • blob: binary large object -- object is a large collection of
uninterpreted binary data (whose interpretation is left to
• Example: time '09:00:30' time '09:00:30.75'
an application outside of the database system)
 timestamp: date plus time of day
• clob: character large object -- object is a large collection
• Example: timestamp '2005-7-27 09:00:30.75' of character data
 interval: period of time  When a query returns a large object, a pointer is returned
• Example: interval '1' day rather than the large object itself.
• Subtracting a date/time/timestamp value from another
gives an interval value
• Interval values can be added to date/time/timestamp
values

Database System Concepts - 7th Edition 4.46 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.47 ©Silberschatz, Korth and Sudarshan

User-Defined Types Domains

 create type construct in SQL creates user-defined type  create domain construct in SQL-92 creates user-defined
domain types
create type Dollars as numeric (12,2) final
create domain person_name char(20) not null
 Example:
 Types and domains are similar. Domains can have
create table department constraints, such as not null, specified on them.
(dept_name varchar (20),
 Example:
building varchar (15),
budget Dollars); create domain degree_level varchar(10)
constraint degree_level_test
check (value in ('Bachelors', 'Masters', 'Doctorate'));

Database System Concepts - 7th Edition 4.48 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.49 ©Silberschatz, Korth and Sudarshan

Index Creation Index Creation Example


 Many queries reference only a small proportion of the records  create table student
in a table. (ID varchar (5),
 It is inefficient for the system to read every record to find a name varchar (20) not null,
record with particular value dept_name varchar (20),
tot_cred numeric (3,0) default 0,
 An index on an attribute of a relation is a data structure that primary key (ID))
allows the database system to find those tuples in the relation
that have a specified value for that attribute efficiently, without  create index studentID_index on student(ID)
scanning through all the tuples of the relation.  The query:
 We create an index with the create index command select *
create index <name> on <relation-name> (attribute); from student
where ID = '12345'
can be executed by using the index to find the required
record, without looking at all records of student

Database System Concepts - 7th Edition 4.50 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.51 ©Silberschatz, Korth and Sudarshan
Authorization Authorization (Cont.)
 We may assign a user several forms of authorizations on  Forms of authorization to modify the database schema
parts of the database. • Index - allows creation and deletion of indices.
• Read - allows reading, but not modification of data. • Resources - allows creation of new relations.
• Insert - allows insertion of new data, but not • Alteration - allows addition or deletion of attributes in a
modification of existing data. relation.
• Update - allows modification, but not deletion of data. • Drop - allows deletion of relations.
• Delete - allows deletion of data.
 Each of these types of authorizations is called a privilege.
We may authorize the user all, none, or a combination of
these types of privileges on specified parts of a database,
such as a relation or a view.

Database System Concepts - 7th Edition 4.52 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.53 ©Silberschatz, Korth and Sudarshan

Authorization Specification in SQL Privileges in SQL


 The grant statement is used to confer authorization  select: allows read access to relation, or the ability to
grant <privilege list> on <relation or view > to <user list> query using the view

 <user list> is: • Example: grant users U1, U2, and U3 select
authorization on the instructor relation:
• a user-id
grant select on instructor to U1, U2, U3
• public, which allows all valid users the privilege
granted  insert: the ability to insert tuples
• A role (more on this later)  update: the ability to update using the SQL update
statement
 Example:
 delete: the ability to delete tuples.
• grant select on department to Amit, Satoshi
 all privileges: used as a short form for all the allowable
 Granting a privilege on a view does not imply granting any privileges
privileges on the underlying relations.
 The grantor of the privilege must already hold the privilege
on the specified item (or be the database administrator).

Database System Concepts - 7th Edition 4.54 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.55 ©Silberschatz, Korth and Sudarshan

Revoking Authorization in SQL Roles


 The revoke statement is used to revoke authorization.  A role is a way to distinguish among various users as far
revoke <privilege list> on <relation or view> from <user as what these users can access/update in the database.
list>  To create a role we use:
 Example: create a role <name>
revoke select on student from U1, U2, U3  Example:
 <privilege-list> may be all to revoke all privileges the • create role instructor
revokee may hold.  Once a role is created we can assign “users” to the role
 If <revokee-list> includes public, all users lose the using:
privilege except those granted it explicitly. • grant <role> to <users>
 If the same privilege was granted twice to the same user
by different grantees, the user may retain the privilege
after the revocation.
 All privileges that depend on the privilege being revoked
are also revoked.

Database System Concepts - 7th Edition 4.56 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.57 ©Silberschatz, Korth and Sudarshan
Roles Example Authorization on Views
 create role instructor;  create view geo_instructor as
 grant instructor to Amit; (select *
from instructor
 Privileges can be granted to roles: where dept_name = 'Geology');
• grant select on takes to instructor;  grant select on geo_instructor to geo_staff
 Roles can be granted to users, as well as to other roles  Suppose that a geo_staff member issues
• create role teaching_assistant • select *
• grant teaching_assistant to instructor; from geo_instructor;
 Instructor inherits all privileges of teaching_assistant  What if
 Chain of roles • geo_staff does not have permissions on instructor?
• create role dean; • creator of view did not have some permissions on
• grant instructor to dean; instructor?

• grant dean to Satoshi;

Database System Concepts - 7th Edition 4.58 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.59 ©Silberschatz, Korth and Sudarshan

Other Authorization Features


 references privilege to create foreign key
• grant reference (dept_name) on department to Mariano;
• why is this required?
 transfer of privileges
• grant select on department to Amit with grant option;
• revoke select on department from Amit, Satoshi cascade; End of Chapter 4
• revoke select on department from Amit, Satoshi restrict;
• And more!

Database System Concepts - 7th Edition 4.60 ©Silberschatz, Korth and Sudarshan Database System Concepts - 7th Edition 4.61 ©Silberschatz, Korth and Sudarshan

You might also like