Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "4.1Database System Concepts - 6 th Edition Chapter 4: Intermediate SQL Join Expressions Views Transactions Integrity Constraints SQL Data Types and Schemas."— Presentation transcript:

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

2 4.2Database System Concepts - 6 th Edition Joined 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.

3 4.3Database System Concepts - 6 th Edition Join 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 的任何資料.

4 4.4Database System Concepts - 6 th Edition Outer 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.

5 4.5Database System Concepts - 6 th Edition Left Outer Join & Right Outer Join course natural left outer join prereq course natural right outer join prereq Note: “natural” 會要求兩個 relation 的共同屬性其值相等.

6 4.6Database System Concepts - 6 th Edition Full Outer Join course natural full outer join prereq

7 4.7Database System Concepts - 6 th Edition Joined 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 (see the next page)

8 4.8Database System Concepts - 6 th Edition Joined Relations – Examples select * from course inner join prereq on course.course_id = prereq.course_id select * from course left outer join prereq on course.course_id = prereq.course_id Note: The joined relations are used as subquery expressions in the from clause

9 4.9Database System Concepts - 6 th Edition Practice 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

10 4.10Database System Concepts - 6 th Edition Views 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.

11 4.11Database System Concepts - 6 th Edition View Definition A view is defined using the create view statement which has the form create view v as where 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.

12 4.12Database System Concepts - 6 th Edition Example 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;

13 4.13Database System Concepts - 6 th Edition Views 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’;

14 4.14Database System Concepts - 6 th Edition View Expansion Expand use of a view in a query/another view create view physics_fall_2009_watson as select course_id, room_number from (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’;

15 4.15Database System Concepts - 6 th Edition Views Defined Using Other Views ※ Views Defined Using Other Views One view may be used in the expression defining another view, A view relation v 1 is said to depend directly on a view relation v 2 if v 2 is used in the expression defining v 1 A view relation v 1 is said to depend on view relation v 2 if either v 1 depends directly to v 2 or there is a path of dependencies from v 1 to v 2 A view relation v is said to be recursive if it depends on itself. V1 V2 V1 V3 V2

16 4.16Database System Concepts - 6 th Edition View Expansion ※ View Expansion Let view v 1 be defined by an expression e 1 that may itself contain uses of view relations. View expansion of an expression repeats the following replacement step: repeat Find any view relation v i in e 1 Replace the view relation v i by the expression defining v i until no more view relations are present in e 1 As long as the view definitions are not recursive, this loop will terminate.

17 4.17Database System Concepts - 6 th Edition Update 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)

18 4.18Database System Concepts - 6 th Edition Some 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)

19 4.19Database System Concepts - 6 th Edition instructor department

20 4.20Database System Concepts - 6 th Edition Transactions 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.

21 4.21Database System Concepts - 6 th Edition Integrity 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)

22 4.22Database System Concepts - 6 th Edition Constraints on a Single Relation Constraints on a Single Relation not null primary key unique check (P), where P is a predicate

23 4.23Database System Concepts - 6 th Edition 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( A 1, A 2, …, A m ) unique ( A 1, A 2, …, A m ) The unique specification states that the attributes A1, A2, … Am form a candidate key. Candidate keys are permitted to be null (in contrast to primary keys).

24 4.24Database System Concepts - 6 th Edition The 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 的物件定義。

25 4.25Database System Concepts - 6 th Edition Referential 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.

26 4.26Database System Concepts - 6 th 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 r 2 is R and the schema of r 1 is S)  is a foreign key of R referencing S Insert. If a tuple t 2 is inserted into r 2, the system must ensure that there is a tuple t 1 in r 1 such that t 1 [  ] = t 2 [  ]. That is t 2 [  ]    (r 1 ) Delete. If a tuple, t 1 is deleted from r 1, the system must compute the set of tuples in r 2 that reference t 1 :   = t 1 [  ] (r 2 ) If this set is not empty, the delete command is rejected.

27 4.27Database System Concepts - 6 th Edition Database Modification (Cont.) Update. There are two cases: If a tuple t 2 is updated in relation r 2 and the update modifies values for foreign key , then a test similar to the insert case is made. Let t 2 ’ denote the new value of tuple t 2. The system must ensure that t 2 ’[  ]    (r 1 ) If a tuple t 1 is updated in r 1, and the update modifies values for the primary key (  ), then a test similar to the delete case is made. The system must compute   = t 1 [  ] (r 2 ) using the old value of t 1 (the value before the update is applied). If this set is not empty, the update may be rejected as an error.

28 4.28Database System Concepts - 6 th Edition Definitions of Cascading Actions in Referential Integrity 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

29 4.29Database System Concepts - 6 th Edition Discussion 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_namebranch_cityassets Perryridge Downtown Brighton Mianus Redwood Horseneck Brooklyn Horseneck Palo Alto 1700000 9000000 7100000 400000 2100000 branch_nameaccount_numberbalance Perryridge Brighton Redwood A-102 A-201 A-217 A-215 A-222 400 900 750 700

30 4.30Database System Concepts - 6 th Edition 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. 各資料庫軟體的做法不同, 一般利用程式語言提供的函數或類別實做。

31 4.31Database System Concepts - 6 th Edition Other 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 等型態

32 4.32Database System Concepts - 6 th Edition User-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)

33 4.33Database System Concepts - 6 th Edition Authorization Specification in SQL The grant statement is used to confer authorization grant on to 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).

34 4.34Database System Concepts - 6 th Edition Privileges in SQL select: allows read access to relation, or the ability to query using the view Example: grant users U 1, U 2, and U 3 select authorization on the department relation: grant select on department to U 1, U 2, U 3 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.

35 4.35Database System Concepts - 6 th Edition Revoking Authorization in SQL The revoke statement is used to revoke authorization. revoke on from Example: revoke select on department from U 1, U 2, U 3 may be all to revoke all privileges the revokee may hold. If includes public, all users lose the privilege except those granted it explicitly.

36 4.36Database System Concepts - 6 th Edition Authorization 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 instructor where 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;


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

Similar presentations


Ads by Google