Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Chapter 4: Immediate SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined."— Presentation transcript:

1 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

2 Derived Relations SQL allows a subquery expression to be used in the from clause 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. Find the average account balance of those branches where the average account balance is greater than $1200. select branch_name, avg_balance from (select branch_name, avg (balance) from account group 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. 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 with max_balance (value) as select max (balance) from account select account_number from account, max_balance where account.balance = max_balance.value Find all accounts with the maximum balance with max_balance (value) as select max (balance) from account select account_number from account, max_balance where account.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. Find all branches where the total account deposit is greater 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

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.) 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 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_number from borrower, loan where borrower.loan_number = loan.loan_number ) (select customer_name, loan_number from borrower, loan where borrower.loan_number = loan.loan_number )

6 View Definition A view is defined using the create view statement which has the form A view is defined using the create view statement which has the form create view v as 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. 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 A 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_name from all_customer where branch_name = ‘Perryridge’

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

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

10 Modification of the Database – Insertion Add a new tuple to account Add a new tuple to account insert into account values (‘A-9732’, ‘Perryridge’,1200) or equivalently insert into account (branch_name, balance, account_number) values (‘Perryridge’, 1200, ‘A-9732’) or equivalently insert into account (branch_name, balance, account_number) values (‘Perryridge’, 1200, ‘A-9732’) Add a new tuple to account with balance set to null Add a new tuple to account with balance set to null insert into account values (‘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 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 account select loan_number, branch_name, 200 from loan where branch_name = ‘Perryridge’ insert into depositor select customer_name, loan_number from loan, borrower where branch_name = ‘ Perryridge’ and loan.account_number =borrower.account_number insert into account select loan_number, branch_name, 200 from loan where branch_name = ‘Perryridge’ insert into depositor select customer_name, loan_number from loan, borrower where 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%. Increase all accounts with balances over $10,000 by 6%, all other accounts receive 5%. Write two update statements: Write two update statements: update account set balance = balance  1.06 where balance > 10000 update account set balance = balance  1.05 where balance  10000 The order is important The order is important Can be done better using the case statement (next slide) 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%. Same query as before: Increase all accounts with balances over $10,000 by 6%, all other accounts receive 5%. update account set balance = case when balance <= 10000 then balance *1.05 else balance * 1.06 end update account set balance = case when balance <= 10000 then balance *1.05 else balance * 1.06 end

14 Update of a View Create a view of all loan data in the loan relation, hiding the amount attribute Create a view of all loan data in the loan relation, hiding the amount attribute create view branch_loan as select branch_name, loan_number from loan Add a new tuple to branch_loan Add a new tuple to branch_loan insert into branch_loan values (‘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 Some insertion to views cannot be translated uniquely insert into all_customer values (‘ Perryridge’, ‘John’) insert into all_customer values (‘ Perryridge’, ‘John’) Have to choose loan or account, and create a new loan/account number! 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 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. Join operations take two relations and return as a result another relation. These additional operations are typically used as subquery expressions in the from clause These additional operations are typically used as subquery expressions in the from clause Join condition – defines which tuples in the two relations match, and what attributes are present in the result of the join. 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. 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 and borrower Note: borrower information missing for L-260 and loan information missing for L-155

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

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

21 Joined Relations – Examples loan full outer join borrower using (loan_number) 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 Integrity Constraints on a Single Relation not null not null primary key primary key unique unique check (P), where P is a predicate check (P), where P is a predicate

23 Not Null and Unique Constraints not null not null Declare name and budget to be not null Declare name and budget to be not null name varchar(20) not null budget numeric(12,2) not null name varchar(20) not null budget numeric(12,2) not null unique ( 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. 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). Candidate keys are permitted to be null (in contrast to primary keys).

24 The check clause check (P) check (P) where P is a predicate 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. 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”. 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. 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 ( 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 department on delete cascade on update cascade,... ) create table course ( … dept_name varchar(20), foreign key (dept_name) references department on delete cascade on update cascade,... ) alternative actions to cascade: set null, set default alternative actions to cascade: set null, set default

27 Integrity Constraint Violation During Transactions E.g. E.g. create table person ( ID char(10), name char(40), mother char(10), father char(10), primary key ID, foreign key father references person, foreign key mother references 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 person insert father and mother of a person before inserting person OR, set father and mother to null initially, update after inserting all persons (not possible if father and mother attributes declared to be not null) OR, set father and mother to null initially, update after inserting all persons (not possible if father and mother attributes declared to be not null) OR defer constraint checking (next slide) OR defer constraint checking (next slide)

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

29 Built-in Data Types in SQL date: Dates, containing a (4 digit) year, month and date date: Dates, containing a (4 digit) year, month and date Example: date ‘2005-7-27’ Example: date ‘2005-7-27’ time: Time of day, in hours, minutes and seconds. time: Time of day, in hours, minutes and seconds. Example: time ‘09:00:30’ time ‘09:00:30.75’ Example: time ‘09:00:30’ time ‘09:00:30.75’ timestamp: date plus time of day timestamp: date plus time of day Example: timestamp ‘2005-7-27 09:00:30.75’ Example: timestamp ‘2005-7-27 09:00:30.75’ interval: period of time interval: period of time Example: interval ‘1’ day Example: interval ‘1’ day Subtracting a date/time/timestamp value from another gives an interval value Subtracting a date/time/timestamp value from another gives an interval value Interval values can be added to date/time/timestamp values 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 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) create index studentID_index on student(ID) Indices are data structures used to speed up access to records with specified values for index attributes Indices are data structures used to speed up access to records with specified values for index attributes e.g. select * from student where ID = ‘12345’ e.g. select * from student where 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 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); 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 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. 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_test check (value in (’Bachelors’, ’Masters’, ’Doctorate’)); create domain degree_level varchar(10) constraint degree_level_test check (value in (’Bachelors’, ’Masters’, ’Doctorate’));

33 Large-Object Types Large objects (photos, videos, CAD files, etc.) are stored as a large object: 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) 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 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. When a query returns a large object, a pointer is returned rather than the large object itself.

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

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

36 Authorization Specification in SQL The grant statement is used to confer authorization The grant statement is used to confer authorization grant grant on to on to is: is: a user-id a user-id Public Public A role A role

37 Privileges in SQL select: allows read access to relation,or the ability to query using the view 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 branch relation: Example: grant users U 1, U 2, and U 3 select authorization on the branch relation: grant select on branch to U 1, U 2, U 3

38 Revoking Authorization in SQL The revoke statement is used to revoke authorization. The revoke statement is used to revoke authorization. revoke revoke on from on from Example: Example: revoke select on branch from U 1, U 2, U 3 may be all to revoke all privileges the revokee may hold. may be all to revoke all privileges the revokee may hold. If includes public, all users lose the privilege except those granted it explicitly. If includes public, all users lose the privilege except those granted it explicitly.

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. 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. All privileges that depend on the privilege being revoked are also revoked.

40 Examples 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;


Download ppt "Chapter 4: Immediate SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined."

Similar presentations


Ads by Google