chapter 4: immediate sql complex queries complex queries views views modification of the database...

40
Chapter 4: Immediate SQL Chapter 4: Immediate SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations Security and Authorization Security and Authorization

Upload: edward-miles

Post on 17-Dec-2015

233 views

Category:

Documents


0 download

TRANSCRIPT

Chapter 4: Immediate SQL Chapter 4: Immediate SQL

Complex Queries Complex Queries ViewsViews Modification of the DatabaseModification of the Database Joined Relations Joined Relations Security and AuthorizationSecurity and Authorization

Derived RelationsDerived Relations SQL allows a subquery expression to be SQL allows a subquery expression to be

used in the used in the from from clauseclause Find the average account balance of Find the average account balance of

those branches where the average those branches where the average account balance is greater than $1200.account balance is greater than $1200.

select select branch_name, avg_balancebranch_name, avg_balancefrom from ((select select branch_name, branch_name, avg avg ((balancebalance))

fromfrom account account group bygroup by branch_name branch_name ))

as as branch_avg branch_avg ( ( branch_name, branch_name, avg_balance avg_balance ))

where where avg_balance > avg_balance > 1200;1200;

With ClauseWith Clause The The withwith clause provides a way of clause provides a way of

defining a temporary view whose defining a temporary view whose definition is available only to the query definition is available only to the query in which the in which the with with clause occurs. clause occurs.

Find all accounts with the maximum Find all accounts with the maximum balance balance

withwith max_balance max_balance ((valuevalue) ) asas selectselect maxmax ( (balancebalance)) fromfrom accountaccount selectselect account_numberaccount_number fromfrom account, max_balanceaccount, max_balance wherewhere account.balance = max_balance.valueaccount.balance = max_balance.value

Complex Query using With Complex Query using With ClauseClause

Find all branches where the total account deposit is greater Find all branches where the total account deposit is greater than the average of the total account deposits at all branches.than the average of the total account deposits at all branches.

with branch_total (branch_name, value) as select branch_name, sum (balance) from account group by branch_name with branch_total_avg (value) as select avg (value) from branch_total select branch_name from branch_total, branch_total_avg where branch_total.value >= branch_total_avg.value

ViewsViews In some cases, it is not desirable for all In some cases, it is not desirable for all

users to see the entire logical model (that users to see the entire logical model (that is, all the actual relations stored in the is, all the actual relations stored in the database.)database.)

Consider a person who needs to know a Consider a person who needs to know a customer’s loan number but has no need to customer’s loan number but has no need to see the loan amount. This person should see the loan amount. This person should see a relation described, in SQL, by see a relation described, in SQL, by

((select select customer_name, loan_numbercustomer_name, loan_number from from borrower, loanborrower, loan where where borrower.loan_number = loan.loan_number borrower.loan_number = loan.loan_number ))

View DefinitionView Definition

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

create view create view v v as as < < query expression >query expression >

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

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

Example QueriesExample Queries A view consisting of branches and their customersA view consisting of branches and their customers

Find all customers of the Perryridge branch

create view all_customer as (select branch_name, customer_name from depositor, account where depositor.account_number =

account.account_number ) union (select branch_name, customer_name from borrower, loan where borrower.loan_number = loan.loan_number )

select customer_namefrom all_customerwhere branch_name = ‘Perryridge’

Modification of the Modification of the Database – DeletionDatabase – Deletion

Delete all account tuples at the Perryridge Delete all account tuples at the Perryridge branchbranch

delete from delete from accountaccountwherewhere branch_name = branch_name = ‘‘PerryridgePerryridge’’

Delete all accounts at every branch located Delete all accounts at every branch located in the city ‘Needham’.in the city ‘Needham’.delete from delete from accountaccountwhere where branch_name branch_name in in ((select select branch_namebranch_name

from from branchbranch where where branch_city = branch_city = ‘‘NeedhamNeedham’’))

Example QueryExample Query

Delete the record of all accounts with Delete the record of all accounts with balances below the average at the bank.balances below the average at the bank. delete from account where balance < (select avg (balance )

from account )

Problem: as we delete tuples from deposit, the average balance changes

Solution used in SQL:

1. First, compute avg balance and find all tuples to delete

2. Next, delete all tuples found above (without recomputing avg or retesting the tuples)

Modification of the Modification of the Database – InsertionDatabase – Insertion

Add a new tuple to Add a new tuple to accountaccount

insert into insert into accountaccountvalues values (‘A-9732’, ‘Perryridge’,1200)(‘A-9732’, ‘Perryridge’,1200)

or equivalentlyor equivalently insert into insert into account account ((branch_name, balance, branch_name, balance, account_numberaccount_number))

values values (‘Perryridge’, 1200, ‘A-9732’)(‘Perryridge’, 1200, ‘A-9732’)

Add a new tuple to Add a new tuple to account account with with balancebalance set to nullset to null

insert into insert into accountaccountvalues values (‘A-777’,‘Perryridge’, (‘A-777’,‘Perryridge’, null null ))

Modification of the Database – Modification of the Database – InsertionInsertion

Provide as a gift for all loan customers of the Provide as a gift for all loan customers of the Perryridge branch, a $200 savings account. Let Perryridge branch, a $200 savings account. Let the loan number serve as the account number the loan number serve as the account number for the new savings accountfor the new savings account

insert into insert into accountaccountselect select loan_number, branch_name, loan_number, branch_name, 200200from from loanloanwhere where branch_name = branch_name = ‘Perryridge’‘Perryridge’

insert into insert into depositordepositorselect select customer_name, loan_numbercustomer_name, loan_numberfrom from loan, borrowerloan, borrowerwhere where branch_name = branch_name = ‘ ‘ Perryridge’Perryridge’ and and loan.account_number loan.account_number

=borrower.account_number=borrower.account_number

Modification of the Modification of the Database – UpdatesDatabase – Updates

Increase all accounts with balances over Increase all accounts with balances over $10,000 by 6%, all other accounts receive 5%.$10,000 by 6%, all other accounts receive 5%. Write two Write two update update statements:statements:

updateupdate account accountset set balance = balance balance = balance 1.06 1.06where where balance balance > 10000> 10000

update update accountaccountsetset balance = balance balance = balance 1.05 1.05where where balance balance 10000 10000

The order is importantThe order is important Can be done better using the Can be done better using the case case statement (next statement (next

slide)slide)

Case Statement for Case Statement for Conditional UpdatesConditional Updates

Same query as before: Increase all Same query as before: Increase all accounts with balances over $10,000 by accounts with balances over $10,000 by 6%, all other accounts receive 5%.6%, all other accounts receive 5%.

updateupdate accountaccount setset balancebalance = = casecase whenwhen balancebalance <= 10000 <= 10000 thenthen balancebalance *1.05*1.05 elseelse balancebalance * 1.06 * 1.06 endend

Update of a ViewUpdate of a View Create a view of all loan data in the Create a view of all loan data in the loanloan

relation, hiding the relation, hiding the amountamount attribute attribute

create view create view branch_loan branch_loan asasselect select branch_name, loan_numberbranch_name, loan_numberfrom from loanloan

Add a new tuple to Add a new tuple to branch_loanbranch_loan

insert into insert into branch_loanbranch_loanvalues values (‘Perryridge’, ‘L-307’)(‘Perryridge’, ‘L-307’)

This insertion must be represented by the This insertion must be represented by the insertion of the tupleinsertion of the tuple

(‘L-307’, ‘Perryridge’, (‘L-307’, ‘Perryridge’, null null ))

into the into the loanloan relation relation

Updates Through Views Updates Through Views (Cont.)(Cont.)

Some insertion to views cannot be Some insertion to views cannot be translated uniquelytranslated uniquely insert into insert into all_customerall_customer values values (‘ (‘ Perryridge’Perryridge’, ,

‘‘JohnJohn’)’) Have to choose loan or account, and Have to choose loan or account, and

create a new loan/account number!create a new loan/account number!

Most SQL implementations allow Most SQL implementations allow updates only on simple views (without updates only on simple views (without aggregates) defined on a single aggregates) defined on a single relationrelation

Joined RelationsJoined Relations Join operationsJoin operations take two relations and return as a take two relations and return as a

result another relation.result another relation. These additional operations are typically used as These additional operations are typically used as

subquery expressions in the subquery expressions in the fromfrom clauseclause Join conditionJoin condition – defines which tuples in the two – defines which tuples in the two

relations match, and what attributes are present in relations match, and what attributes are present in the result of the join.the result of the join.

Join typeJoin type – defines how tuples in each relation that – defines how tuples in each relation that do not match any tuple in the other relation (based do not match any tuple in the other relation (based on the join condition) are treated.on the join condition) are treated.

Joined RelationsJoined Relations

Joined Relations – Datasets Joined Relations – Datasets for Examplesfor Examples

Relation loan and borrower

Note: borrower information missing for L-260 and loan information missing for L-155

Joined Relations – Joined Relations – Examples Examples

loan loan inner join inner join borrower borrower ononloan.loan_number = borrower.loan_numberloan.loan_number = borrower.loan_number

loan left outer join borrower onloan.loan_number = borrower.loan_number

Joined Relations – ExamplesJoined Relations – Examples

loan loan natural inner joinnatural inner join borrowerborrower

loan natural right outer join borrower

Joined Relations – ExamplesJoined Relations – Examples loan loan full outer join full outer join borrower borrower using using ((loan_numberloan_number))

Find all customers who have either an account or a loan (but not both) at the bank.

select customer_namefrom (depositor natural full outer join borrower )where account_number is null or loan_number is null

Integrity Constraints on a Single Integrity Constraints on a Single

RelationRelation not nullnot null primary keyprimary key uniqueunique check check (P), where P is a predicate(P), where P is a predicate

Not Null and Unique Not Null and Unique Constraints Constraints

not nullnot null Declare Declare namename and and budgetbudget to be to be not nullnot null

name name varcharvarchar(20) (20) not nullnot null budget budget numericnumeric(12,2) (12,2) not nullnot null

uniqueunique ( ( AA11, , AA22, …, , …, AAmm))

The unique specification states that the attributes The unique specification states that the attributes AA1, 1, AA2, … 2, … AAmmform a candidate key.form a candidate key.

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

The check clauseThe check clause check check (P)(P)

where P is a predicatewhere 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), check (semester in (’Fall’, ’Winter’, ’Spring’, ’Summer’)));

Referential IntegrityReferential Integrity Ensures that a value that appears in one relation for a Ensures that a value that appears in one relation for a

given set of attributes also appears for a certain set of given set of attributes also appears for a certain set of attributes in another relation.attributes in another relation. Example: If “Biology” is a department name Example: If “Biology” is a department name

appearing in one of the tuples in the appearing in one of the tuples in the instructorinstructor relation, then there exists a tuple in the relation, then there exists a tuple in the departmentdepartment relation for “Biology”. relation for “Biology”.

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

Cascading Actions in Referential Cascading Actions in Referential IntegrityIntegrity

create table create table course (course ( course_id course_id charchar(5) (5) primary keyprimary key,, title title varcharvarchar(20),(20), dept_name dept_name varcharvarchar(20) (20) references references departmentdepartment))

create table create table course course (( … … dept_name dept_name varcharvarchar(20),(20), foreign key foreign key ((dept_namedept_name) ) references references departmentdepartment on delete cascadeon delete cascade on update cascade on update cascade,, . . . . . . ))

alternative actions to cascade: alternative actions to cascade: set nullset null, , set defaultset default

Integrity Constraint Violation During Integrity Constraint Violation During TransactionsTransactions

E.g.E.g.

create table create table person person ((IDID charchar(10),(10),name name charchar(40),(40),mothermother charchar(10),(10),father father char char(10),(10),primary keyprimary key ID, ID,foreign key foreign key fatherfather references references person,person,foreign key foreign key mothermother references references person person))

How to insert a tuple without causing constraint violation ?How to insert a tuple without causing constraint violation ? insert father and mother of a person before inserting insert father and mother of a person before inserting

personperson OR, set father and mother to null initially, update after OR, set father and mother to null initially, update after

inserting all persons (not possibleinserting all persons (not possible ifif father and mother father and mother

attributes declaredattributes declared to be to be not nullnot null) ) OR defer constraintOR defer constraint checking (next slide)checking (next slide)

Complex Check ClausesComplex Check Clauses

check check ((time_slot_id time_slot_id in in ((select select time_slot_id time_slot_id from from time_slottime_slot)))) why not use a foreign key here?why not use a foreign key here?

Every section has at least one instructor teaching the Every section has at least one instructor teaching the section.section. how to write this?how to write this?

Unfortunately: subquery in check clause not supported by Unfortunately: subquery in check clause not supported by pretty much any databasepretty much any database Alternative: triggers (later)Alternative: triggers (later)

create assertion create assertion <assertion-name> <assertion-name> check check <predicate>;<predicate>; Also not supported by anyoneAlso not supported by anyone

Built-in Data Types in SQL Built-in Data Types in SQL

date:date: Dates, containing a (4 digit) year, month and date Dates, containing a (4 digit) year, month and date Example: Example: datedate ‘2005-7-27’ ‘2005-7-27’

time: time: Time of day, in hours, minutes and seconds. Time of day, in hours, minutes and seconds. Example: Example: time time ‘09:00:30’ ‘09:00:30’ time time ‘09:00:30.75’ ‘09:00:30.75’

timestamptimestamp: date plus time of day: date plus time of day Example: Example: timestamptimestamp ‘2005-7-27 09:00:30.75’ ‘2005-7-27 09:00:30.75’

interval:interval: period of time period of time Example: interval ‘1’ dayExample: interval ‘1’ day Subtracting a date/time/timestamp value from Subtracting a date/time/timestamp value from

another gives an interval valueanother gives an interval value Interval values can be added to date/time/timestamp Interval values can be added to date/time/timestamp

valuesvalues

Index CreationIndex Creation

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

create index create index studentID_index studentID_index on on studentstudent((IDID)) Indices are data structures used to speed up access to records Indices are data structures used to speed up access to records

with specified values for index attributeswith specified values for index attributes e.g. e.g. select * select *

from from studentstudent where where ID = ID = ‘12345’‘12345’

can be executed by using the index to find the required record, can be executed by using the index to find the required record, without looking at all records of without looking at all records of studentstudent

More on indices in Chapter 11More on indices in Chapter 11

User-Defined TypesUser-Defined Types create type create type construct in SQL creates user-defined construct in SQL creates user-defined

typetype

create type create type DollarsDollars as numeric (12,2) as numeric (12,2) final final

create table create table departmentdepartment((dept_name dept_name varchar varchar (20),(20),building building varchar varchar (15),(15),budget Dollarsbudget Dollars););

DomainsDomains

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

create domain create domain person_name person_name charchar(20) (20) not nullnot null

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

create domain create domain degree_level degree_level varcharvarchar(10)(10)constraint constraint degree_level_testdegree_level_testcheck check ((value in value in (’Bachelors’, ’Masters’, ’Doctorate’));(’Bachelors’, ’Masters’, ’Doctorate’));

Large-Object TypesLarge-Object Types

Large objects (photos, videos, CAD files, etc.) are stored as Large objects (photos, videos, CAD files, etc.) are stored as a a large objectlarge object:: blobblob: binary large object -- object is a large collection of : binary large object -- object is a large collection of

uninterpreted binary data (whose interpretation is left to uninterpreted binary data (whose interpretation is left to an application outside of the database system)an application outside of the database system)

clobclob: character large object -- object is a large collection : character large object -- object is a large collection of character dataof character data

When a query returns a large object, a pointer is When a query returns a large object, a pointer is returned rather than the large object itself.returned rather than the large object itself.

AuthorizationAuthorizationForms of authorization on parts of the Forms of authorization on parts of the

database:database:

Select Select - allows reading, but not - allows reading, but not

modification of data.modification of data. Insert Insert - allows insertion of new data, but - allows insertion of new data, but

not modification of existing data.not modification of existing data. Update Update - allows modification, but not - allows modification, but not

deletion of data.deletion of data. Delete Delete - allows deletion of data.- allows deletion of data.

AuthorizationAuthorization

Forms of authorization to modify the Forms of authorization to modify the database schema database schema

Index Index - allows creation and deletion of - allows creation and deletion of indices.indices.

Resources Resources - allows creation of new - allows creation of new relations.relations.

Alteration Alteration - allows addition or deletion of - allows addition or deletion of attributes in a relation.attributes in a relation.

Drop Drop - allows deletion of relations.- allows deletion of relations.

Authorization Specification Authorization Specification in SQLin SQL

The The grantgrant statement is used to confer statement is used to confer authorizationauthorization

grantgrant <privilege list> <privilege list>

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

<user list> is:<user list> is: a user-ida user-id PublicPublic A role A role

Privileges in SQLPrivileges in SQL

selectselect:: allows read access to relation,or allows read access to relation,or the ability to query using the viewthe ability to query using the view Example: grant users Example: grant users UU11, , UU22, and , and UU33 selectselect

authorization on the authorization on the branch branch relation:relation:

grant select on grant select on branch branch to to UU11, U, U22, U, U33

Revoking Authorization in Revoking Authorization in SQLSQL The The revokerevoke statement is used to statement is used to

revoke authorization.revoke authorization.revoke revoke <privilege list><privilege list>

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

Example:Example:revoke select on revoke select on branch branch from from UU11, U, U22, U, U33

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

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

Revoking Authorization in Revoking Authorization in SQLSQL

If the same privilege was granted twice to If the same privilege was granted twice to the same user by different grantees, the the same user by different grantees, the user may retain the privilege after the user may retain the privilege after the revocation.revocation.

All privileges that depend on the privilege All privileges that depend on the privilege being revoked are also revoked.being revoked are also revoked.

ExamplesExamples

grant select on branch to public;grant select on branch to public; revoke select on branch from public;revoke select on branch from public; grant select, insert on branch to public;grant select, insert on branch to public; grant all privilege on branch to public;grant all privilege on branch to public; revoke all privilege on branch from public;revoke all privilege on branch from public; revoke select on branch from public;revoke select on branch from public;