1 / 40

Chapter 4: Immediate SQL

Chapter 4: Immediate SQL . Complex Queries Views Modification of the Database Joined Relations Security and Authorization. Derived Relations. SQL allows a subquery expression to be used in the from clause

isabella
Download Presentation

Chapter 4: Immediate SQL

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Derived Relations • SQL allows a subquery expression to be used in the from clause • Find the average account balance of those branches where the average account balance is greater than $1200. select branch_name, avg_balancefrom (select branch_name, avg (balance)from accountgroup by branch_name )as branch_avg ( branch_name, avg_balance )where avg_balance > 1200;

  3. With Clause • The with clause provides a way of defining a temporary view whose definition is available only to the query in which the with clause occurs. • Find all accounts with the maximum balance withmax_balance (value) asselectmax (balance)fromaccountselectaccount_numberfromaccount, max_balancewhereaccount.balance = max_balance.value

  4. Complex Query using With Clause • Find all branches where the total account deposit is greater than the average of the total account deposits at all branches. withbranch_total (branch_name, value) asselectbranch_name, sum (balance)fromaccountgroupbybranch_namewithbranch_total_avg (value) asselectavg (value)frombranch_totalselect branch_namefrombranch_total, branch_total_avg wherebranch_total.value >= branch_total_avg.value

  5. 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.) • Consider a person who needs to know a customer’s loan number but has no need to see the loan amount. This person should see a relation described, in SQL, by (select customer_name, loan_numberfrom borrower, loanwhere borrower.loan_number = loan.loan_number )

  6. View 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.

  7. Example Queries • A view consisting of branches and their customers create view all_customer as(select branch_name, customer_namefrom depositor, accountwhere depositor.account_number = account.account_number ) union(select branch_name, customer_namefrom borrower, loanwhere borrower.loan_number = loan.loan_number ) • Find all customers of the Perryridge branch select customer_namefrom all_customerwhere branch_name = ‘Perryridge’

  8. Modification of the Database – Deletion • Delete all account tuples at the Perryridge branch delete from accountwhere branch_name = ‘Perryridge’ • Delete all accounts at every branch located in the city ‘Needham’. delete from accountwhere branch_name in (select branch_namefrom branchwhere branch_city = ‘Needham’)

  9. Example Query • Delete the record of all accounts with balances below the average at the bank. delete from accountwhere 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)

  10. Modification of the Database – Insertion • Add a new tuple to account insert into accountvalues (‘A-9732’, ‘Perryridge’,1200) or equivalentlyinsert into account (branch_name, balance, account_number)values (‘Perryridge’, 1200, ‘A-9732’) • Add a new tuple to account with balance set to null insert into accountvalues (‘A-777’,‘Perryridge’, null )

  11. Modification of the Database – Insertion • Provide as a gift for all loan customers of the Perryridge branch, a $200 savings account. Let the loan number serve as the account number for the new savings account insert into accountselect loan_number, branch_name, 200from loanwhere branch_name = ‘Perryridge’insert into depositorselect customer_name, loan_numberfrom loan, borrowerwhere branch_name = ‘ Perryridge’ and loan.account_number =borrower.account_number

  12. Modification of the Database – Updates • Increase all accounts with balances over $10,000 by 6%, all other accounts receive 5%. • Write two update statements: update accountset balance = balance  1.06where balance > 10000 update accountset balance = balance  1.05where balance  10000 • The order is important • Can be done better using the case statement (next slide)

  13. Case Statement for Conditional Updates • Same query as before: Increase all accounts with balances over $10,000 by 6%, all other accounts receive 5%. updateaccountsetbalance = casewhenbalance <= 10000 thenbalance *1.05elsebalance * 1.06end

  14. Update of a View • Create a view of all loan data in the loan relation, hiding the amount attribute create view branch_loan as select branch_name, loan_numberfrom loan • Add a new tuple to branch_loan insert into branch_loanvalues (‘Perryridge’, ‘L-307’) This insertion must be represented by the insertion of the tuple (‘L-307’, ‘Perryridge’, null ) into the loan relation

  15. Updates Through Views (Cont.) • Some insertion to views cannot be translated uniquely • insert into all_customer values (‘ Perryridge’, ‘John’) • Have to choose loan or account, and create a new loan/account number! • Most SQL implementations allow updates only on simple views (without aggregates) defined on a single relation

  16. Joined Relations • Join operations take two relations and return as a result another relation. • These additional operations are typically used as subquery expressions in the fromclause • 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.

  17. Joined Relations

  18. Joined Relations – Datasets for Examples • Relation loan andborrower • Note: borrower information missing for L-260 and loan information missing for L-155

  19. Joined Relations – Examples • loan inner join borrower onloan.loan_number = borrower.loan_number • loan left outer join borrower onloan.loan_number = borrower.loan_number

  20. Joined Relations – Examples • loan natural inner joinborrower • loan natural right outer join borrower

  21. Joined Relations – Examples • loan full outer join borrower using (loan_number) • Find all customers who have either an account or a loan (but not both) at the bank. select customer_name from (depositor natural full outer join borrower ) where account_number is null or loan_number is null

  22. Integrity Constraints on a Single Relation • not null • primary key • unique • check (P), where P is a predicate

  23. Not Null and Unique Constraints • not null • Declare name and budget to be not null name varchar(20) not nullbudget numeric(12,2) not null • 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).

  24. 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), check(semester in (’Fall’, ’Winter’, ’Spring’, ’Summer’)));

  25. 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. • Example: If “Biology” is a department name appearing in one of the tuples in the instructor relation, then there exists a tuple in the department relation for “Biology”. • Let A be a set of attributes. Let R and S be two 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 for any values of A appearing in R these values also appear in S.

  26. Cascading Actions in Referential Integrity • create table course ( course_id char(5) primary key,title varchar(20), dept_name varchar(20) references department) • create table course ( …dept_name varchar(20),foreign key (dept_name) references departmenton delete cascade on update cascade, . . . ) • alternative actions to cascade: set null, set default

  27. Integrity Constraint Violation During Transactions • E.g. create table person (IDchar(10),name char(40),motherchar(10),father char(10),primary key ID,foreign key father references person,foreign key motherreferences person) • How to insert a tuple without causing constraint violation ? • insert father and mother of a person before inserting person • OR, set father and mother to null initially, update after inserting all persons (not possibleiffather and mother attributes declaredto be not null) • OR defer constraintchecking (next slide)

  28. Complex Check Clauses • check (time_slot_id in (select time_slot_id from time_slot)) • why not use a foreign key here? • Every section has at least one instructor teaching the section. • how to write this? • Unfortunately: subquery in check clause not supported by pretty much any database • Alternative: triggers (later) • create assertion <assertion-name> check <predicate>; • Also not supported by anyone

  29. Built-in 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’ • interval: period of time • Example: interval ‘1’ day • Subtracting a date/time/timestamp value from another gives an interval value • Interval values can be added to date/time/timestamp values

  30. Index Creation • 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)) • create index studentID_index on student(ID) • Indices are data structures used to speed up access to records with specified values for index attributes • e.g. select * from studentwhere ID = ‘12345’ can be executed by using the index to find the required record, without looking at all records of student More on indices in Chapter 11

  31. User-Defined Types • create type construct in SQL creates user-defined type create type Dollars as numeric (12,2) final • create table department(dept_name varchar (20),building varchar (15),budget Dollars);

  32. Domains • create domain construct in SQL-92 creates user-defined domain types create domain person_name char(20) not null • Types and domains are similar. Domains can have constraints, such as not null, specified on them. • create domain degree_level varchar(10)constraint degree_level_testcheck (value in (’Bachelors’, ’Masters’, ’Doctorate’));

  33. Large-Object Types • Large objects (photos, videos, CAD files, etc.) are stored as a large object: • blob: binary large object -- object is a large collection of uninterpreted binary data (whose interpretation is left to an application outside of the database system) • clob: character large object -- object is a large collection of character data • When a query returns a large object, a pointer is returned rather than the large object itself.

  34. Forms of authorization on parts of the database: Select - allows reading, but not modification of data. Insert - allows insertion of new data, but not modification of existing data. Update - allows modification, but not deletion of data. Delete - allows deletion of data. Authorization

  35. Authorization Forms of authorization to modify the database schema • Index - allows creation and deletion of indices. • Resources - allows creation of new relations. • Alteration - allows addition or deletion of attributes in a relation. • Drop - allows deletion of relations.

  36. 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 A role Authorization Specification in SQL

  37. select: allows read access to relation,or the ability to query using the view Example: grant users U1, U2, and U3select authorization on the branch relation: grant select on branch to U1, U2, U3 Privileges in SQL

  38. The revokestatement is used to revoke authorization. revoke <privilege list> on <relation name or view name> from <user list> Example: revoke select on branch 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. Revoking Authorization in SQL

  39. Revoking Authorization in SQL • If the same privilege was granted twice to the same user by different grantees, the user may retain the privilege after the revocation. • All privileges that depend on the privilege being revoked are also revoked.

  40. Examples • grant select on branch to public; • revoke select on branch from public; • grant select, insert on branch to public; • grant all privilege on branch to public; • revoke all privilege on branch from public; • revoke select on branch from public;

More Related