4.1database system concepts - 6 th edition chapter 4: intermediate sql join expressions views...

36
4.1 atabase System Concepts - 6 th Edition Chapter 4: Intermediate SQL Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas Authorization

Upload: nelson-davidson

Post on 31-Dec-2015

237 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.1Database System Concepts - 6th Edition

Chapter 4: Intermediate SQLChapter 4: Intermediate SQL

Join Expressions

Views

Transactions

Integrity Constraints

SQL Data Types and Schemas

Authorization

Page 2: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.2Database System Concepts - 6th Edition

Joined RelationsJoined Relations

Join operations take two relations and return as a result another relation.

A join operation is a Cartesian product which requires that tuples in the two relations match (under some condition). It also specifies the attributes that are present in the result of the join.

The join operations are typically used as subquery expressions in the from clause.

Page 3: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.3Database System Concepts - 6th Edition

Join operations – ExampleJoin operations – Example

Relation course

Relation prereq

Note: prereq information missing for CS-315 and course information missing for CS-437. course prereq 會沒有 CS-315 和 CS-437 的任何資料 .

Page 4: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.4Database System Concepts - 6th Edition

Outer JoinOuter Join

An extension of the join operation that avoids loss of information.

Computes the join and then adds tuples form one relation that does not match tuples in the other relation to the result of the join.

Uses null values.

The join operations we studied earlier that do not preserve nonmatched tuples are called inner join operations.

Page 5: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.5Database System Concepts - 6th Edition

Left Outer JoinLeft Outer Join && Right Outer JoinRight Outer Join

course natural left outer join prereq

course natural right outer join prereq

Note: “natural” 會要求兩個 relation 的共同屬性其值相等 .

Page 6: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.6Database System Concepts - 6th Edition

Full Outer JoinFull Outer Join

course natural full outer join prereq

Page 7: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.7Database System Concepts - 6th Edition

Joined RelationsJoined Relations

Join operations take two relations and return as a result another relation.

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 match any tuple in the other relation (based on the join condition) are treated.

大部分的軟體支援 (inner, left outer, right outer) join + on <predicate>

(see the next page)

Page 8: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.8Database System Concepts - 6th Edition

Joined Relations – Examples Joined Relations – Examples

select * from course inner join prereq oncourse.course_id = prereq.course_id

select * from course left outer join prereq oncourse.course_id = prereq.course_id

Note: The joined relations are used as subquery expressions in the from clause

Page 9: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.9Database System Concepts - 6th Edition

PracticePractice

Find the course_ids and sec_ids which were offered by an instructor named “Einstein”, using the “inner join” expression.

Answer:

(1) using “natural” expression

(2) Using “on” expression

(3) Using “using” expression

Page 10: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.10Database System Concepts - 6th Edition

ViewsViews

In some cases, it is not desirable for all users to see the entire logical model (that is, all the actual relations stored in the database.) (see page 1.6)

Consider a person who needs to know an instructors name and department, but not the salary. This person should see a relation described, in SQL, by

select ID, name, dept_name from instructor

A view provides a mechanism to hide certain data from the view of certain users.

Any relation that is not of the conceptual model but is made visible to a user as a “virtual relation” is called a view.

Page 11: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.11Database System Concepts - 6th Edition

View DefinitionView Definition

A view is defined using the create view statement which has the form

create view v as < query expression >

where <query expression> is any legal SQL expression. The view name is represented by v.

Once a view is defined, the view name can be used to refer to the virtual relation that the view generates.

View definition is not the same as creating a new relation by evaluating the query expression

Rather, a view definition causes the saving of an expression; the expression is substituted into queries using the view.

Page 12: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.12Database System Concepts - 6th Edition

Example ViewsExample Views

A view of instructors without their salary

create view faculty as select ID, name, dept_name from instructor;

Find all instructors in the Biology department select name from faculty where dept_name = ‘Biology’;

(c.f. page 3.54)

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;

Page 13: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.13Database System Concepts - 6th Edition

Views Defined Using Other ViewsViews Defined Using Other Views

create view physics_fall_2009 as select course.course_id, sec_id, building, room_number from course, section where course.course_id = section.course_id and course.dept_name = ’Physics’ and section.semester = ’Fall’ and section.year = ’2009’;

create view physics_fall_2009_watson as select course_id, room_number from physics_fall_2009 where building= ’Watson’;

Page 14: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.14Database System Concepts - 6th Edition

View ExpansionView Expansion

Expand use of a view in a query/another view

create view physics_fall_2009_watson asselect course_id, room_numberfrom (select course.course_id, building, room_number

from course, section where course.course_id = section.course_id and course.dept_name = ’Physics’ and section.semester = ’Fall’ and section.year = ’2009’)

where building= ’Watson’;

Page 15: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.15Database System Concepts - 6th Edition

※ Views Defined Using Other ViewsViews Defined Using Other Views

One view may be used in the expression defining another view,

A view relation v1 is said to depend directly on a view relation v2 if v2 is used in the expression defining v1

A view relation v1 is said to depend on view relation v2 if either v1

depends directly to v2 or there is a path of dependencies from v1 to v2

A view relation v is said to be recursive if it depends on itself.

V1

V2

V1

V3

V2

Page 16: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.16Database System Concepts - 6th Edition

※ View ExpansionView Expansion

Let view v1 be defined by an expression e1 that may itself contain uses of view relations.

View expansion of an expression repeats the following replacement step:

repeatFind any view relation vi in e1

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.

Page 17: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.17Database System Concepts - 6th Edition

Update of a ViewUpdate of a View

Add a new tuple to faculty view which we defined earlier

insert into faculty values (’30765’, ’Green’, ’Music’);

This insertion must be represented by the insertion of the tuple

(’30765’, ’Green’, ’Music’, null)

into the instructor relation.

30765 Green Music

30765 Green Music Null

faculty (ID, name, dept_name)

instructor (ID, name, dept_name, salary)

Page 18: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.18Database System Concepts - 6th Edition

Some Updates cannot be Translated UniquelySome Updates cannot be Translated Uniquely

create view instructor_info as select ID, name, building from instructor, department where instructor.dept_name= department.dept_name;

insert into instructor_info values (’69987’, ’White’, ’Painter’);

(see the next page for the effects on the relations)

which department, if multiple departments in Painter?

無法決定 department 內對應資料列的 PK 值 !

Most SQL implementations allow updates only on simple views

The from clause has only one database relation.

The query does not have a group by or having clause.

Any attribute not listed in the select clause can be set to null.

The select clause contains only attribute names of the relation, and does not have any expressions, aggregates, or distinct specification. (see page 4.12)

Page 19: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.19Database System Concepts - 6th Edition

instructor department

Page 20: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.20Database System Concepts - 6th Edition

TransactionsTransactions A transaction is a sequence of queries and update statements executed as

a single unit.

Motivating example (see page 1.4) Transfer of money from one account to another involves two steps:

(1) deduct from one account (2) credit to another

If one steps succeeds and the other fails, database is in an inconsistent state. Therefore, either both steps should succeed or neither should

Transaction should be atomic, that is, indivisible.

Transactions can be terminated by one of commit work: makes all updates of the transaction permanent in the database

rollback work: undoes all updates performed by the transaction.

But default on most databases: each SQL statement commits automatically

Can turn off auto commit using API (see Chapter 5).

In SQL:1999, can use begin atomic …. End to declare a transaction.

Page 21: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.21Database System Concepts - 6th Edition

Integrity ConstraintsIntegrity Constraints

Integrity constraints guard against accidental damage to the database, by ensuring that authorized changes to the database do not result in a loss of data consistency.

A checking account must have a balance greater than $10,000.00.

A salary of a bank employee must be at least $4.00 an hour.

A customer must have a (non-null) phone number.

When an integrity constraint is violated, the normal procedure is to reject the action that caused the violation.

Types of integrity constraints

Constraints on a single relation

Constraints on two relations (Referential Integrity)

Page 22: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.22Database System Concepts - 6th Edition

Constraints on a Single Relation Constraints on a Single Relation

not null

primary key

unique

check (P), where P is a predicate

Page 23: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.23Database System Concepts - 6th Edition

Not Null and Unique Constraints Not Null and Unique Constraints

not null

Declare name and budget to be not null

name varchar(20) not null budget numeric(12,2) not null

primary key( A1, A2, …, Am)

unique ( A1, A2, …, Am)

The unique specification states that the attributes A1, A2, … Amform a candidate key.

Candidate keys are permitted to be null (in contrast to primary keys).

Page 24: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.24Database System Concepts - 6th Edition

The check clauseThe check clause

check (P): where P is a predicate

Example: ensure that semester is one of fall, winter, spring or summer:

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), constraint sem_test check (semester in (’Fall’, ’Winter’, ’Spring’, ’Summer’))); The clause constraint sem_test is optional; it can give a

name to the constraint.

此功能可在資料庫裡宣告,或利用如 asp.net 的物件定義。

Page 25: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.25Database System Concepts - 6th Edition

Referential IntegrityReferential Integrity

Ensures that a value that appears in one relation for a given set of attributes also appears for a certain set of attributes in another relation. (see page 2.8) Example: If “Comp. Sci.” is a department name appearing in

one of the tuples in the instructor relation, then there exists a tuple in the department relation for “Comp. Sci.”.

Let be a set of attributes. Let R and S be two relations that contain attributes , where is the primary key of S. is said to be a foreign key of R if for any values of appearing in R these values also appear in S. R is the referencing relation and S is the referenced relation.

When a referential-integrity constraint is violated, the normal procedure is to reject the action that caused the violation.

(see the next two pages) Otherwise, we can define “cascading” action. That is, if a delete or

update action on the “referenced” relation violates the constraint, the system automatically change the corresponding tuples in the referencing relation to make the constraint being satisfied.

Page 26: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.26Database System Concepts - 6th Edition

Checking Referential Integrity on Database Modification

The following tests must be made in order to preserve the following referential integrity constraint: (the schema of r2 is R and the schema

of r1 is S)

is a foreign key of R referencing S

Insert. If a tuple t2 is inserted into r2, the system must ensure that there is a tuple t1 in r1 such that t1[] = t2[]. That is

t2 [] (r1)

Delete. If a tuple, t1 is deleted from r1, the system must compute the

set of tuples in r2 that reference t1:

= t1[] (r2)

If this set is not empty, the delete command is rejected.

Page 27: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.27Database System Concepts - 6th Edition

Database Modification (Cont.)

Update. There are two cases:

If a tuple t2 is updated in relation r2 and the update modifies values

for foreign key , then a test similar to the insert case is made. Let t2’ denote the new value of tuple t2. The system must ensure

that

t2’[] (r1)

If a tuple t1 is updated in r1, and the update modifies values for the

primary key (), then a test similar to the delete case is made. The system must compute

= t1[] (r2)

using the old value of t1 (the value before the update is applied). If

this set is not empty, the update may be rejected as an error.

Page 28: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.28Database System Concepts - 6th Edition

Definitions of Cascading Actions in Referential Definitions of Cascading Actions in Referential IntegrityIntegrity

create table course ( course_id char(5), title varchar(20), dept_name varchar(20),

primary key (course_id),

foreign key (dept_name) references department)

<- rejected if violated create table course (

… dept_name varchar(20),

primary key (course_id),

foreign key (dept_name) references department on delete cascade on update cascade )

<- delete and update can be defined differently

Page 29: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.29Database System Concepts - 6th Edition

DiscussionDiscussion For the following two tables, suppose branch_name in the account

relation is a foreign key referencing the branch table. When will the referential constraint be violated? (Consider the case of insert, delete, update).

branch

account

branch_name branch_city assets

PerryridgeDowntownBrightonMianusRedwood

HorseneckBrooklynBrooklyn

HorseneckPalo Alto

170000090000007100000400000

2100000

branch_name account_number balance

PerryridgePerryridgeBrightonBrightonRedwood

A-102A-201A-217A-215A-222

400900750750700

Page 30: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.30Database System Concepts - 6th Edition

More Data Types in SQL More Data Types in SQL

date: Dates, containing a (4 digit) year, month and date

Example: date ‘2005-7-27’

time: Time of day, in hours, minutes and seconds.

Example: time ‘09:00:30’ time ‘09:00:30.75’

timestamp: date plus time of day

Example: timestamp ‘2005-7-27 09:00:30.75’ 附註

在 MS SQL 和 MySQL 中,有 date, time, datetime 等型態

We need functions to convert a character string to the type above. We also need functions to get the current time. 各資料庫軟體的做法不同 , 一般利用程式語言提供的函數或類別實做

Page 31: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.31Database System Concepts - 6th Edition

Other FeaturesOther Features

Default value

create table student(ID varchar (5),name varchar (20) not null,dept_name varchar (20),tot_cred numeric (3,0) default 0,primary key (ID));

index

create index studentID_index on student(ID);

Large objects

book_review clob(10KB)

附註: In MS SQL ,提供 text 型態 image blob(10MB)

movie blob(2GB)

附註: In MS SQL ,提供 binary, image 等型態

Page 32: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.32Database System Concepts - 6th Edition

User-Defined TypesUser-Defined Types

create domain construct in SQL-92 creates user-defined domain types

create domain person_name char(20) not null

create table instructor ( ID char(5), name person_name, dept_name varchar(20), salary numeric(8,2));

create type construct in SQL:99 creates user-defined type

create type Dollars as numeric (12,2) final

Types and domains are similar. Domains can have constraints, such as not null, specified on them. Types can be more complex.

各軟體支援的功能和語法差異很大 . (see page 141 in text)

Page 33: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.33Database System Concepts - 6th Edition

Authorization Specification in SQLAuthorization Specification in SQL

The grant statement is used to confer authorization

grant <privilege list>

on <relation name or view name> to <user list>

<user list> is:

a user-id  (資料庫的帳號) public, which allows all valid users the privilege granted

A role: a class of users

The grantor of the privilege must already hold the privilege on the specified item (or be the database administrator).

Page 34: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.34Database System Concepts - 6th Edition

Privileges in SQLPrivileges in SQL

select: allows read access to relation, or the ability to query using the view

Example: grant users U1, U2, and U3 select authorization on the department relation:

grant select on department to U1, U2, U3

insert: the ability to insert tuples.

update: the ability to update using the SQL update statement.

delete: the ability to delete tuples.

all privileges: used as a short form for all the allowable privileges.

Page 35: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.35Database System Concepts - 6th Edition

Revoking Authorization in SQLRevoking Authorization in SQL

The revoke statement is used to revoke authorization.

revoke <privilege list>

on <relation name or view name> from <user list>

Example:

revoke select on department from U1, U2, U3

<privilege-list> may be all to revoke all privileges the revokee may hold.

If <revokee-list> includes public, all users lose the privilege except those granted it explicitly.

Page 36: 4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas

4.36Database System Concepts - 6th Edition

Authorization on ViewsAuthorization on Views

Granting a privilege on a view does not imply granting any privileges on the underlying relations. (see page 4.11)

Users can be given authorization on views, without being given any authorization on the relations used in the view definition. This can limit a user’s access to precisely the data that user needs.

Suppose a staff is allowed to see only the salaries of all faculty in the Geology department.

Approach create view geo_instructor as

(select *from instructorwhere dept_name = ’Geology’);

grant select on geo_instructor to staff This staff is authorized to see the result of the following query:

select *from geo_instructor;