Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification...

35
Chapter 4: SQL Chapter 4: 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 Embedded SQL/ODBC/JDBC Embedded SQL/ODBC/JDBC

Transcript of Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification...

Page 1: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

Chapter 4: SQL Chapter 4: SQL

Complex Queries Complex Queries ViewsViews Modification of the DatabaseModification of the Database Joined Relations Joined Relations Security and AuthorizationSecurity and Authorization Embedded SQL/ODBC/JDBCEmbedded SQL/ODBC/JDBC

Page 2: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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;

Page 3: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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

Page 4: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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

Page 5: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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

Page 6: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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.

Page 7: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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’

Page 8: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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

Page 9: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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)

Page 10: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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

Page 11: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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

Page 12: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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)

Page 13: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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

Page 14: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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

Page 15: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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

Page 16: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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.

Page 17: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

Joined RelationsJoined Relations

Page 18: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined 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

Page 19: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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

Page 20: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

Joined Relations – ExamplesJoined Relations – Examples

loan loan natural inner joinnatural inner join borrowerborrower

loan natural right outer join borrower

Page 21: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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

Page 22: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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.

Page 23: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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.

Page 24: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined 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

Page 25: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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

Page 26: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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.

Page 27: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

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.

Page 28: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

Examples in OracleExamples in Oracle

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;

Page 29: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

Embedded SQLEmbedded SQL The SQL standard defines embeddings of SQL The SQL standard defines embeddings of SQL

in a variety of programming languages such as in a variety of programming languages such as C, Java, and Cobol.C, Java, and Cobol.

A language to which SQL queries are A language to which SQL queries are embedded is referred to as a embedded is referred to as a host languagehost language, , and the SQL structures permitted in the host and the SQL structures permitted in the host language comprise language comprise embedded embedded SQL.SQL.

EXEC SQLEXEC SQL statement is used to identify statement is used to identify embedded SQL request to the preprocessorembedded SQL request to the preprocessor

EXEC SQL <embedded SQL statement > EXEC SQL <embedded SQL statement >

END_EXECEND_EXEC

Page 30: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

Example QueryExample Query Specify the query in SQL and declare a Specify the query in SQL and declare a cursorcursor

for itfor it EXEC SQLEXEC SQL

declare declare cc cursor for cursor for select select customer_name, customer_citycustomer_name, customer_city from from depositor, customer, accountdepositor, customer, account where where depositor.customer_name = customer.customer_name depositor.customer_name = customer.customer_name andand depositor account_number = account.account_number depositor account_number = account.account_number

and and account.balance > :amountaccount.balance > :amount

END_EXECEND_EXEC

Page 31: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

Embedded SQL (Cont.)Embedded SQL (Cont.) TheThe open open statement causes the query to be statement causes the query to be

evaluatedevaluated

EXEC SQL EXEC SQL openopen cc END_EXECEND_EXEC The The fetchfetch statement causes the values of one statement causes the values of one

tuple in the query result to be placed on host tuple in the query result to be placed on host language variables.language variables.

EXEC SQLEXEC SQL fetch fetch c c into into ::cn, :cccn, :cc END_EXEC END_EXECRepeated calls to Repeated calls to fetchfetch get successive tuples get successive tuples in the query resultin the query result

The The close close statement causes the database statement causes the database system to delete the temporary relation that system to delete the temporary relation that holds the result of the query.holds the result of the query.

EXEC SQL EXEC SQL closeclose cc END_EXEC END_EXEC

Page 32: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

Updates Through CursorsUpdates Through Cursors Can update tuples fetched by cursor by declaring that the cursor

is for update

declare c cursor for select * from account where branch_name = ‘Perryridge’ for update

To update tuple at the current location of cursor c

update account set balance = balance + 100 where current of c

Page 33: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

Dynamic SQLDynamic SQL

Allows programs to construct and submit Allows programs to construct and submit SQL queries at run time.SQL queries at run time.

Example of the use of dynamic SQL from Example of the use of dynamic SQL from within a C program.within a C program.char * char * sqlprog = “ sqlprog = “update update account account setset balance = balance * balance = balance * 1.051.05

where where account_number account_number = ?”= ?”EXEC SQL EXEC SQL prepareprepare dynprog dynprog from from :sqlprog;:sqlprog;charchar account account [10] = “A-101”;[10] = “A-101”;EXEC SQL EXEC SQL execute execute dynprogdynprog using using :account;:account;

Page 34: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

ODBC and JDBCODBC and JDBC API (application-program interface) for a API (application-program interface) for a

program to interact with a database serverprogram to interact with a database server Application makes calls toApplication makes calls to

Connect with the database serverConnect with the database server Send SQL commands to the database serverSend SQL commands to the database server Fetch tuples of result one-by-one into program Fetch tuples of result one-by-one into program

variablesvariables ODBC (Open Database Connectivity) works ODBC (Open Database Connectivity) works

with C, C++, C#, and Visual Basicwith C, C++, C#, and Visual Basic JDBC (Java Database Connectivity) works with JDBC (Java Database Connectivity) works with

JavaJava

Page 35: Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.

JDBCJDBC JDBCJDBC is a Java API for communicating with is a Java API for communicating with

database systems supporting SQLdatabase systems supporting SQL JDBC also supports metadata retrieval, such as JDBC also supports metadata retrieval, such as

querying about relations present in the querying about relations present in the database and the names and types of relation database and the names and types of relation attributesattributes

Model for communicating with the database:Model for communicating with the database: Open a connectionOpen a connection Create a “statement” objectCreate a “statement” object Execute queries using the Statement object to send Execute queries using the Statement object to send

queries and fetch resultsqueries and fetch results Exception mechanism to handle errorsException mechanism to handle errors