62
Chapter 4: SQL Chapter 4: SQL Basic Structure Basic Structure Data Definition Language Data Definition Language Modification of the Database Modification of the Database Set Operations Set Operations Aggregate Functions Aggregate Functions Null Values Null Values Nested Subqueries Nested Subqueries Derived Relations Derived Relations Views Views Joined Relations Joined Relations

Chapter 4: SQL Basic Structure Data Definition Language Modification of the Database Set Operations Aggregate Functions Null Values Nested

Embed Size (px)

Citation preview

Page 1: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Chapter 4: SQLChapter 4: SQL Basic Structure Basic Structure Data Definition Language Data Definition Language Modification of the DatabaseModification of the Database Set OperationsSet Operations Aggregate FunctionsAggregate Functions Null ValuesNull Values Nested SubqueriesNested Subqueries Derived RelationsDerived Relations ViewsViews Joined RelationsJoined Relations

Page 2: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Schema Used in ExamplesSchema Used in Examples

Page 3: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Data Definition Language (DDL)Data Definition Language (DDL)

The The schemaschema for each relation. for each relation. The The domaindomain of each attribute. of each attribute. Integrity constraints.Integrity constraints. The set of The set of indicesindices to be maintained. to be maintained. Security and authorizationSecurity and authorization information for information for

each relation.each relation. The The physical storagephysical storage structure of each structure of each

relation on disk.relation on disk.

Allows the specification of not only a set of relations but also information about each relation, including:

Page 4: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Domain Types in SQLDomain Types in SQLchar(n).char(n). Fixed length character string, with user-specified length Fixed length character string, with user-specified length n.n.

varchar(n).varchar(n). Variable length character strings, with user-specified Variable length character strings, with user-specified maximum length maximum length n.n.

int.int. Integer (a finite subset of the integers that is machine-dependent).Integer (a finite subset of the integers that is machine-dependent).

smallintsmallint.. Small integer (a machine-dependent subset of the integer Small integer (a machine-dependent subset of the integer domain type).domain type).

numeric(p,d).numeric(p,d). Fixed point number, with user-specified precision of Fixed point number, with user-specified precision of pp digits, with digits, with nn digits to the right of decimal point. digits to the right of decimal point.

real, double precision.real, double precision. Floating point and double-precision floating Floating point and double-precision floating point numbers, with machine-dependent precision.point numbers, with machine-dependent precision.

float(n).float(n). Floating point number, with user-specified precision of at Floating point number, with user-specified precision of at least least nn digits. digits.

Null valuesNull values are allowed in all the domain types. Declaring an are allowed in all the domain types. Declaring an attribute to be not null prohibits null values for that attribute.attribute to be not null prohibits null values for that attribute.

create domaincreate domain construct in SQL-92 creates user-defined domain construct in SQL-92 creates user-defined domain typestypes

create domain create domain person-name person-name charchar(20) (20) not nullnot null

Page 5: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Date/Time Types in SQLDate/Time Types in SQLdate.date. Dates, containing a (4 digit) year, month and date Dates, containing a (4 digit) year, month and date

E.g. E.g. datedate ‘2001-7-27’ ‘2001-7-27’

time. time. Time of day, in hours, minutes and seconds. Time of day, in hours, minutes and seconds. E.g. E.g. 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 E.g. E.g. timestamptimestamp ‘2001-7-27 09:00:30.75’ ‘2001-7-27 09:00:30.75’

IntervalInterval:: period of time period of time E.g. Interval ‘1’ dayE.g. Interval ‘1’ day Subtracting a date/time/timestamp value from another gives an Subtracting a date/time/timestamp value from another gives an

interval valueinterval value Interval values can be added to date/time/timestamp valuesInterval values can be added to date/time/timestamp values

Can extract values of individual fields from date/time/timestampCan extract values of individual fields from date/time/timestamp E.g. E.g. extractextract ( (year fromyear from r.starttime) r.starttime)

Can cast string types to date/time/timestamp Can cast string types to date/time/timestamp E.g. E.g. castcast <string-valued-expression> <string-valued-expression> as dateas date

Page 6: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Create Table ConstructCreate Table Construct An SQL relation is defined using the An SQL relation is defined using the create table create table

command:command:

create table create table r r ((AA11 DD11, , AA22 DD22, ..., , ..., AAnn D Dnn,,

(integrity-constraint(integrity-constraint11),),

...,...,(integrity-constraint(integrity-constraintkk))))

rr is the name of the relation is the name of the relation each each AAii is an attribute name in the schema of relation is an attribute name in the schema of relation rr

DDii is the data type of values in the domain of attribute is the data type of values in the domain of attribute AAii

Example:Example: create table create table branchbranch((branch-name branch-name char(15) char(15) not null,not null,branch-city branch-city char(30),char(30),assetsassets integer)integer)

Page 7: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Integrity Constraints in Integrity Constraints in Create TableCreate Table

not nullnot null primary keyprimary key ( (AA11, ..., , ..., AAnn)) check check (P)(P),, where where PP is a predicate is a predicate uniqueunique ( (AA11, ..., , ..., AAnn))

Example: Declare branch-name as the primary key for branch and ensure that the values of assets are non-negative.

create table branch(branch-name char(15),branch-city char(30)assets integer,primary key (branch-name),check (assets >= 0))

Page 8: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Drop and Alter Table ConstructsDrop and Alter Table Constructs The The drop tabledrop table command deletes all information about command deletes all information about

the dropped relation from the database.the dropped relation from the database. The The alter tablealter table command is used to add attributes to command is used to add attributes to

an existing relation. an existing relation.

alter table alter table r r add add A DA D

where where AA is the name of the attribute to be added to relation is the name of the attribute to be added to relation r r and and DD is the domain of is the domain of A. A. All tuples in the relation are assigned All tuples in the relation are assigned nullnull as the value for the new attribute. as the value for the new attribute.

The The alter tablealter table command can also be used to drop command can also be used to drop attributes of a relationattributes of a relation

alter table alter table rr drop drop A A

where where AA is the name of an attribute of relation is the name of an attribute of relation r r Dropping of attributes not supported by many Dropping of attributes not supported by many

databasesdatabases

Page 9: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Modification of the Database Modification of the Database (DML) – Insertion(DML) – 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 equivalentlyinsert into insert into account (branch-name, balance, account-account (branch-name, balance, account-number)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 set to nullto null

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

Page 10: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Modification of the Database Modification of the Database – Deletion– Deletion

Delete all account records at the Perryridge Delete all account records at the Perryridge branchbranch

delete from delete from accountaccountwherewhere branch-name = branch-name = ‘‘PerryridgePerryridge’’

Page 11: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Modification of the Database Modification of the Database – Updates– Updates

Increase all accounts with balances over $10,000 by Increase all accounts with balances over $10,000 by 6%, all other accounts receive 5%.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 accountaccount setset balance = balance balance = balance 1.05 1.05 where 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 statementstatement

Page 12: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Case Statement for Conditional Case Statement for Conditional UpdatesUpdates

Same query as before: Increase all accounts Same query as before: Increase all accounts with balances over $10,000 by 6%, all other with balances over $10,000 by 6%, all other accounts receive 5%.accounts receive 5%.updateupdate account account setset balancebalance = = casecase

whenwhen balancebalance <= 10000 <= 10000 thenthen balancebalance *1.05 *1.05

elseelse balancebalance * 1.06 * 1.06endend

Page 13: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

DML query language DML query language SQL is based on set and relational operations SQL is based on set and relational operations

with certain modifications and enhancementswith certain modifications and enhancements A typical A typical SQL querySQL query has the form: has the form:

select select AA11, , AA22, ..., , ..., AAnn

fromfrom rr11, , rr22, ..., , ..., rrmm

where where PP AAiis s represent attributesrepresent attributes

rriis s represent relationsrepresent relations PP is a predicate. is a predicate.

This query is equivalent to the relational algebra This query is equivalent to the relational algebra expression expression AA11, A2, ..., An, A2, ..., An((P P (r(r1 1 x x rr2 2 x ... x x ... x rrmm))))

The result of an SQL query is a relation.The result of an SQL query is a relation.

Page 14: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

The select ClauseThe select Clause The The selectselect clause list the attributes desired in the clause list the attributes desired in the

result of a queryresult of a query corresponds to the projection operation of the relational corresponds to the projection operation of the relational

algebraalgebra Find the names of all branches in the Find the names of all branches in the loanloan relation relation

select select branch-name branch-name from from loanloan In the “pure” relational algebra syntax, the query would In the “pure” relational algebra syntax, the query would

be be branch-namebranch-name((loan)loan) NOTE: SQL does not permit the ‘-’ character in names, NOTE: SQL does not permit the ‘-’ character in names,

Use, e.g., Use, e.g., branch_namebranch_name instead of instead of branch-namebranch-name in a real in a real implementation.implementation.

NOTE: SQL names are case insensitive, i.e. you can use NOTE: SQL names are case insensitive, i.e. you can use capital or small letters. capital or small letters. You may wishYou may wish to use upper case where-ever we use bold to use upper case where-ever we use bold

font.font.

Page 15: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

The select Clause (Cont.)The select Clause (Cont.) SQL allows duplicates in relations as well as in query SQL allows duplicates in relations as well as in query

results.results. To force the elimination of duplicates, insert the To force the elimination of duplicates, insert the

keyword keyword distinctdistinct after after selectselect.. Find the names of all branches in the Find the names of all branches in the loanloan relations, relations,

and remove duplicatesand remove duplicates

select distinct select distinct branch-namebranch-namefrom from loanloan

The keyword The keyword allall specifies that duplicates not be specifies that duplicates not be removed.removed.

select allselect all branch-namebranch-namefrom from loanloan

Page 16: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

The select Clause (Cont.)The select Clause (Cont.) An asterisk in the select clause denotes “all attributes”An asterisk in the select clause denotes “all attributes”

select select **from from loanloan

The The selectselect clause can contain arithmetic expressions clause can contain arithmetic expressions involving the operation, +, –, involving the operation, +, –, , and /, and operating on , and /, and operating on constants or attributes of tuples.constants or attributes of tuples.

The query: The query:

selectselect loan-number, branch-name, amount loan-number, branch-name, amount 100 100 from from loanloan

would return a relation which is the same as the would return a relation which is the same as the loan loan relations, except that the attribute relations, except that the attribute amount amount is multiplied is multiplied by 100.by 100.

Page 17: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

The where ClauseThe where Clause The The wherewhere clause specifies conditions that the result clause specifies conditions that the result

must satisfymust satisfy corresponds to the selection predicate of the relational corresponds to the selection predicate of the relational

algebra. algebra. To find all loan number for loans made at the To find all loan number for loans made at the

Perryridge branch with loan amounts greater than Perryridge branch with loan amounts greater than $1200.$1200.select select loan-numberloan-numberfrom from loanloanwhere where branch-name = ‘branch-name = ‘PerryridgePerryridge’ ’ and and amount amount > 1200> 1200

Comparison results can be combined using the logical Comparison results can be combined using the logical connectives connectives andand, , oror, , and and notnot..

Comparisons can be applied to results of arithmetic Comparisons can be applied to results of arithmetic expressions.expressions.

Page 18: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

The where Clause (Cont.)The where Clause (Cont.) SQL includes a SQL includes a betweenbetween comparison operator comparison operator

Ex: Find the loan number of those loans with Ex: Find the loan number of those loans with loan amounts between $90,000 and $100,000 loan amounts between $90,000 and $100,000 (that is, (that is, $90,000 and $90,000 and $100,000)$100,000)

select loan-numberfrom loanwhere amount between 90000 and 100000

Page 19: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

The from ClauseThe from Clause The The fromfrom clause lists the relations involved in the clause lists the relations involved in the

queryquery corresponds to the Cartesian product operation of corresponds to the Cartesian product operation of

the relational algebra.the relational algebra. Find the Cartesian product Find the Cartesian product borrower x loanborrower x loan

select select from from borrower, loanborrower, loan

Find the name, loan number and loan amount of all customers having a loan at the Perryridge branch.

select customer-name, borrower.loan-number, amountfrom borrower, loanwhere borrower.loan-number = loan.loan-number and branch-name = ‘Perryridge’

Page 20: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

The Rename OperationThe Rename Operation The SQL allows The SQL allows renamingrenaming relations and relations and

attributes using the attributes using the as as clause:clause:old-name old-name asas new-name new-name

Find the name, loan number and loan Find the name, loan number and loan amount of all customers; rename the amount of all customers; rename the column name column name loan-number loan-number as as loan-id.loan-id.

select customer-name, borrower.loan-number as loan-id, amountfrom borrower, loanwhere borrower.loan-number = loan.loan-number

Page 21: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Tuple VariablesTuple Variables Tuple variables are defined in the Tuple variables are defined in the fromfrom clause via the clause via the

use of the use of the as as clause.clause. Find the customer names and their loan numbers for Find the customer names and their loan numbers for

all customers having a loan at some branch.all customers having a loan at some branch.

select distinct T.branch-name from branch as T, branch as S where T.assets > S.assets and S.branch-city = ‘Brooklyn’

Find the names of all branches that have greater assets than some branch located in Brooklyn.

select customer-name, T.loan-number, S.amount from borrower as T, loan as S where T.loan-number = S.loan-number

Page 22: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

String OperationsString Operations SQL includes a string-matching operator for SQL includes a string-matching operator for

comparisons on character strings. Patterns are comparisons on character strings. Patterns are described using two special characters:described using two special characters: percent (percent (%%). The % character matches any substring.). The % character matches any substring. underscore (underscore (__). The _ character matches any ). The _ character matches any

character.character. Find the names of all customers whose street includes Find the names of all customers whose street includes

the substring “Main”.the substring “Main”.

select select customer-namecustomer-namefrom from customercustomerwherewhere customer-street customer-street like like ‘‘%Main%%Main%’’

SQL supports a variety of string operations such as SQL supports a variety of string operations such as concatenation, converting from upper to lower case, concatenation, converting from upper to lower case, finding string length, extracting substrings, etc.finding string length, extracting substrings, etc.

Page 23: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Ordering the Display of TuplesOrdering the Display of Tuples List in alphabetic order the names of all List in alphabetic order the names of all

customers having a loan in Perryridge branchcustomers having a loan in Perryridge branch

select distinct select distinct customer-namecustomer-namefrom from borrower, loanborrower, loanwhere where borrower loan-number = loan.loan-number borrower loan-number = loan.loan-number andand branch-name = branch-name = ‘‘PerryridgePerryridge’’order by order by customer-namecustomer-name

We may specify We may specify descdesc for descending order or for descending order or asc for ascending order, for each attribute; asc for ascending order, for each attribute; ascending order is the default.ascending order is the default. E.g. E.g. order byorder by customer-namecustomer-name descdesc

Page 24: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Set OperationsSet Operations The set operations The set operations unionunion, , intersectintersect, , and and

exceptexcept operate on relations and correspond to operate on relations and correspond to the relational algebra operations the relational algebra operations

Each of the above operations automatically Each of the above operations automatically eliminates duplicates; to retain all duplicates eliminates duplicates; to retain all duplicates use the corresponding multiset versions use the corresponding multiset versions union union all, intersect allall, intersect all andand except allexcept all.. Suppose a tuple occurs Suppose a tuple occurs mm times in times in rr and and n n times in times in

s, s, then, it occurs:then, it occurs:• m m + n + n times in times in r r union all union all ss

• min(min(m,n)m,n) times in times in rr intersect all intersect all ss• max(0, max(0, m – n)m – n) times in times in rr except all except all ss

Page 25: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Set OperationsSet Operations

Find all customers who have a loan, an Find all customers who have a loan, an account, or both:account, or both:

(select customer-name from depositor)except(select customer-name from borrower)

(select customer-name from depositor)intersect(select customer-name from borrower)

Find all customers who have an account but no loan.

(select customer-name from depositor)union(select customer-name from borrower)

Find all customers who have both a loan and an account.

Page 26: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Aggregate FunctionsAggregate Functions

These functions operate on the multiset These functions operate on the multiset of values of a column of a relation, and of values of a column of a relation, and return a valuereturn a value

avgavg: : average valueaverage valueminmin: : minimum valueminimum valuemaxmax: : maximum valuemaximum valuesumsum: : sum of valuessum of valuescountcount: : number of valuesnumber of values

Page 27: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Aggregate Functions (Cont.)Aggregate Functions (Cont.) Find the average account balance at the Find the average account balance at the

Perryridge branch.Perryridge branch.

Find the number of depositors in the bank.

Find the number of tuples in the customer relation.

select avg (balance)from accountwhere branch-name = ‘Perryridge’

select count (*)from customer

select count (distinct customer-name)from depositor

g avg(balance) (branch-name= “Perryridge” account)

Page 28: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Aggregate Functions and Aggregate Functions and Group ByGroup By

Find the total balance for each branch.Find the total balance for each branch.

Attributes in select clause outside of aggregate functions must appear in group by list

select branch-name, sum (balance) as sum-balancefrom accountgroup by branch-name

•branch-name g branch-name, sum(balance) as sum-balance (account)

Page 29: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Aggregate Functions – Having Aggregate Functions – Having ClauseClause

Find the names of all branches where the average Find the names of all branches where the average account balance is more than $1,200.account balance is more than $1,200.

Predicates in the having clause are applied after the formation of groups whereas predicates in the where clause are applied before forming groupsThe expressions appearing in the having clause must have a single value per group => a column appearing in the having clause must appear as the argument to an aggregate operator or must also appear in the group by clause

select branch-name, avg (balance)from accountgroup by branch-namehaving avg (balance) > 1200

Page 30: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Null ValuesNull Values It is possible for tuples to have a null value, denoted by It is possible for tuples to have a null value, denoted by

nullnull, for some of their attributes, for some of their attributes nullnull signifies an unknown value or that a value does signifies an unknown value or that a value does

not exist.not exist. The predicate The predicate is nullis null can be used to check for null can be used to check for null

values.values.

Ex. Find all loan number which appear in the Ex. Find all loan number which appear in the loanloan relation with null values for relation with null values for amount.amount.

selectselect loan-number loan-numberfromfrom loan loanwhere where amount amount is nullis null

The result of any The result of any arithmetic expression involving arithmetic expression involving nullnull is is null (null (E.g. 5 + null returns null)E.g. 5 + null returns null)

Page 31: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Null Values and Three Valued Null Values and Three Valued LogicLogic

Any Any comparison with comparison with nullnull returns returns unknownunknown E.g. 5 < null or null <> null or null = nullE.g. 5 < null or null <> null or null = null

Three-valued logicThree-valued logic using the truth value using the truth value unknownunknown:: OROR: (: (unknownunknown oror truetrue) = ) = truetrue, (, (unknownunknown oror falsefalse) = ) =

unknown,unknown, ( (unknown unknown oror unknown) = unknown unknown) = unknown ANDAND:: (true (true and and unknown) = unknown, (falseunknown) = unknown, (false and and

unknown) = false, (unknown unknown) = false, (unknown andand unknown) = unknown unknown) = unknown NOTNOT: (: (notnot unknown) = unknown unknown) = unknown ““PP is unknown is unknown” ” evaluates to true if predicate evaluates to true if predicate PP

evaluates to evaluates to unknownunknown Result of Result of where where clause predicateclause predicate is treated as is treated as false false if if

it evaluates to it evaluates to unknownunknown

Page 32: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Null Values and AggregatesNull Values and Aggregates All aggregate operations except All aggregate operations except count(*)count(*) ignore ignore

tuplestuples with null values on the aggregated with null values on the aggregated attributes.attributes.Ex: Total all loan amountsEx: Total all loan amounts

select sumselect sum ( (amount)amount)fromfrom loan loan

Above statement Above statement ignores null amountsignores null amounts result is nullresult is null if there is no non-null amount if there is no non-null amount

The The countcount of an of an emptyempty collection is collection is 00, all other , all other aggregate functions return aggregate functions return nullnull when applied to when applied to an empty collectionan empty collection

Page 33: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Nested SubqueriesNested Subqueries

SQL provides a mechanism for the SQL provides a mechanism for the nesting of nesting of subqueriessubqueries..

A subquery is a A subquery is a select-from-whereselect-from-where expression that is nested within another expression that is nested within another query.query.

A common use of subqueries is to A common use of subqueries is to perform tests for set membership, set perform tests for set membership, set comparisons, and set cardinality.comparisons, and set cardinality.

Page 34: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Set membership - examplesSet membership - examples Find all customers who have both an Find all customers who have both an

account and a loan at the bank.account and a loan at the bank.

Find all customers who have a loan at the bank but do not have an account at the bank

select distinct customer-namefrom borrowerwhere customer-name not in (select customer-name

from depositor)

select distinct customer-namefrom borrowerwhere customer-name in (select customer-name

from depositor)

Page 35: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Set membership – examples Set membership – examples (cont.)(cont.)

Find all customers who have both an Find all customers who have both an account and a loan at the Perryridge account and a loan at the Perryridge branchbranch

select distinct customer-namefrom borrower, loanwhere borrower.loan-number = loan.loan-number and

branch-name = “Perryridge” and (branch-name, customer-name) in

(select branch-name, customer-namefrom depositor, accountwhere depositor.account-number =

account.account-number)

Page 36: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Set Comparison – some or anySet Comparison – some or any Find all branches that have greater Find all branches that have greater

assets than some branch located in assets than some branch located in Brooklyn.Brooklyn.

Same query using > some clauseselect branch-name

from branchwhere assets > some (select assets from branch

where branch-city = ‘Brooklyn’)

select distinct T.branch-namefrom branch as T, branch as Swhere T.assets > S.assets and S.branch-city = ‘Brooklyn’

Page 37: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Definition of Some ClauseDefinition of Some ClauseF <comp> F <comp> some some rr t t rr s.t. ( s.t. (F <comp> F <comp> tt))

Where <comp> can be: Where <comp> can be:

056

(5< some ) = true

05

0

) = false

5

05(5 some ) = true (since 0 5)

(read: 5 < some tuple in the relation)

(5< some

) = true(5 = some

(= some) inHowever, ( some) not in

Page 38: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Set Comparison – allSet Comparison – all

Find the names of all branches that Find the names of all branches that have greater assets than all branches have greater assets than all branches located in Brooklyn.located in Brooklyn.

select branch-namefrom branchwhere assets > all

(select assetsfrom branchwhere branch-city = ‘Brooklyn’)

Page 39: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Definition of all ClauseDefinition of all Clause F <comp> F <comp> all all rr t t rr (F <comp> (F <comp> t)t)

056

(5< all ) = false

6104

) = true

5

46(5 all ) = true (since 5 4 and 5 6)

(5< all

) = false(5 = all

( all) not inHowever, (= all) in

Page 40: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Test for Empty RelationsTest for Empty Relations

The The existsexists construct returns the value construct returns the value truetrue if if the argument subquery is nonempty.the argument subquery is nonempty.

exists exists r r r r ØØnot exists not exists r r r r = = ØØ

Find all customers who have both an account Find all customers who have both an account and a loan at the bankand a loan at the bank

select customer_name from borrowerselect customer_name from borrower

where exists (select * from depositor where where exists (select * from depositor where depositor.customer_name=borrower.customer_name)depositor.customer_name=borrower.customer_name)

Page 41: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Example QueryExample Query Find all customers who have an account Find all customers who have an account

at all branches located in Brooklynat all branches located in Brooklynselect distinct S.customer-name

from depositor as Swhere not exists (

(select branch-namefrom branchwhere branch-city = ‘Brooklyn’)

except(select R.branch-namefrom depositor as T, account as Rwhere T.account-number = R.account-number and

S.customer-name = T.customer-name)) Note that X – Y = Ø X Y

Note: Cannot write this query using = all and its variants

Page 42: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Example Query (cont.)Example Query (cont.)

Find all customers who have an account Find all customers who have an account at all branches located in Brooklynat all branches located in Brooklyn

select distinct S.customer-namefrom depositor as Swhere not exists (select branch-name

from branch as B

where branch-city = ‘Brooklyn’

and not exists (select R.branch-name from depositor as T, account as R where T.account-number = R.account-number

and R. branch-name = B.branch-name

and S.customer-name = T.customer-name)

Page 43: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Test for Absence of Duplicate Test for Absence of Duplicate TuplesTuples

The The uniqueunique construct tests whether a subquery construct tests whether a subquery has any duplicate tuples in its result.has any duplicate tuples in its result.

Ex: Find all customers who have at most one Ex: Find all customers who have at most one account at the Perryridge branch.account at the Perryridge branch.

select T.customer-namefrom depositor Twhere unique (

select R.customer-namfrom account, depositor Rwhere T.customer-name = R.customer-name and

R.account-number = account.account-number and account.branch-name = ‘Perryridge’)

Page 44: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Example QueryExample Query

Find all customers who have at least two Find all customers who have at least two accounts at the Perryridge branch. accounts at the Perryridge branch.

select distinct T.customer-namefrom depositor Twhere not unique (

select R.customer-namefrom account, depositor as Rwhere T.customer-name = R.customer-name

andR.account-number = account.account-number

andaccount.branch-name = ‘Perryridge’)

Page 45: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

ViewsViews

Provide a mechanism to hide certain Provide a mechanism to hide certain data from the view of certain users. To data from the view of certain users. To create a view we use the command:create a view we use the command:create view v as <query expression>

where:<query expression> is any legal expressionThe view name is represented by v

Page 46: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

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

customerscustomers

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 47: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Derived RelationsDerived Relations Find the average account balance of those branches Find the average account balance of those branches

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

select select branch-name, avg-balancebranch-name, avg-balancefrom (select from (select branch-name, branch-name, avg avg (balance)(balance) fromfrom account account

group bygroup by branch-name) branch-name) as as result (branch-name, avg-balance)result (branch-name, avg-balance)

where where avg-balance > avg-balance > 12001200

Note that we do not need to use the Note that we do not need to use the having having clause, since clause, since we compute the temporary (view) relation we compute the temporary (view) relation resultresult in the in the from from clause, and the attributes of clause, and the attributes of resultresult can be used can be used directly in the directly in the where where clause.clause.

Page 48: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Another ExampleAnother Example Find the maximum across all branches of the Find the maximum across all branches of the

total balance at each branchtotal balance at each branch

select select max(tot_balance)max(tot_balance)

from (select from (select branch-name, branch-name, sum sum (balance)(balance)

fromfrom account account

group bygroup by branch-name) branch-name) branch_total(branch_name, tot_balance)branch_total(branch_name, tot_balance)

Aggregate functions cannot be composed (ex: Aggregate functions cannot be composed (ex: max(sum(...)) is not allowed)max(sum(...)) is not allowed)

Page 49: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

With ClauseWith Clause

WithWith clause allows views to be defined clause allows views to be defined locally to a query, rather than globally. locally to a query, rather than globally. Analogous to procedures in a Analogous to procedures in a programming language.programming language.

Find all accounts with the maximum Find all accounts with the maximum balance balance withwith max-balancemax-balance((valuevalue) ) asas selectselect max ( max (balancebalance)) fromfrom accountaccount selectselect account-numberaccount-number fromfrom account, max-balanceaccount, max-balance wherewhere account.balance = max-balance.valueaccount.balance = max-balance.value

Page 50: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Complex Query using With Complex Query using With ClauseClause

Find all branches where the total account deposit is Find all branches where the total account deposit is greater than the average of the total account deposits at greater than the average of the total account deposits at all branches.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 51: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

More on Insertion More on Insertion

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

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 = borrower.account-number loan.account-number = borrower.account-number

The select from where statement is fully evaluated before The select from where statement is fully evaluated before any of its results are inserted into the relationany of its results are inserted into the relation

Page 52: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

More on DeletionMore on Deletion Delete all accounts at every branch located in Delete all accounts at every branch located in

Needham city.Needham city.

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

delete from delete from depositordepositorwhere where account-number account-number in in ((select select account-numberaccount-number

from from branch, accountbranch, account where where branch-city = branch-city = ‘‘NeedhamNeedham’’ and and branch.branch-name = account.branch-branch.branch-name = account.branch-

name)name)

Page 53: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

More on Deletion (cont.)More on Deletion (cont.)

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 54: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Update of a ViewUpdate of a View Create a view of all loan data in Create a view of all loan data in loanloan relation, hiding relation, hiding

the the amount amount attributeattribute

create view create view branch-loan branch-loan asasselect select branch-name, loan-number branch-name, loan-number from from loanloan

Add a new tuple to Add a new tuple to branch-loanbranch-loan

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

This insertion must be represented by the insertion of This insertion must be represented by the insertion of the tuple the tuple (‘L-307’, ‘Perryridge’, (‘L-307’, ‘Perryridge’, nullnull) ) into the into the loanloan relation relation

Updates on more complex views are difficult or Updates on more complex views are difficult or impossible to translate, and hence are disallowed. impossible to translate, and hence are disallowed. Most SQL implementations allow updates only on Most SQL implementations allow updates only on

simple views (without aggregates) defined on a simple views (without aggregates) defined on a single relationsingle relation

Page 55: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

TransactionsTransactions A A transactiontransaction is a sequence of queries and update is a sequence of queries and update

statements executed as a single unitstatements executed as a single unit Transactions are started implicitly and terminated by one ofTransactions are started implicitly and terminated by one of

• commit workcommit work: : makes all updates of the transaction makes all updates of the transaction permanent in the databasepermanent in the database

• rollback workrollback work: : undoes all updates performed by the undoes all updates performed by the transaction. transaction.

Ex: Transfer of money from one account to another Ex: Transfer of money from one account to another involves two steps: 1) deduct from one account and 2) involves two steps: 1) deduct from one account and 2) credit to anothercredit to another If one steps succeeds and the other fails, database is in an If one steps succeeds and the other fails, database is in an

inconsistent stateinconsistent state Therefore, either both steps should succeed or neither Therefore, either both steps should succeed or neither

shouldshould If any step of a transaction fails, all work done by the If any step of a transaction fails, all work done by the

transaction can be undone by transaction can be undone by rollback work. rollback work. Rollback of incomplete transactions is done automatically, Rollback of incomplete transactions is done automatically,

in case of system failures in case of system failures

Page 56: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Transactions (Cont.)Transactions (Cont.) In most database systems, each SQL In most database systems, each SQL

statement that executes successfully is statement that executes successfully is automatically committed. automatically committed. Each transaction would then consist of only a single Each transaction would then consist of only a single

statementstatement Automatic commit can usually be turned off, Automatic commit can usually be turned off,

allowing multi-statement transactions, but how to allowing multi-statement transactions, but how to do so depends on the database systemdo so depends on the database system

Another option in SQL:1999: enclose statements Another option in SQL:1999: enclose statements withinwithin begin atomicbegin atomic … … end end

Page 57: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

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

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

expressions in the expressions in the from from clauseclause Join conditionJoin condition – defines which tuples in the two relations – defines which tuples in the two relations

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

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

Join Typesinner joinleft outer joinright outer joinfull outer join

Join Conditions

naturalon <predicate>using (A1, A2, ..., An)

Page 58: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Joined Relations – Datasets Joined Relations – Datasets for Examplesfor Examples

Relation Relation loanloan

Relation borrower

customer-name loan-number

Jones

Smith

Hayes

L-170

L-230

L-155

amount

3000

4000

1700

branch-name

Downtown

Redwood

Perryridge

loan-number

L-170

L-230

L-260

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

Page 59: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Joined Relations – Examples Joined Relations – Examples loan loan inner join inner join borrower borrower onon

loan.loan-number = borrower.loan-numberloan.loan-number = borrower.loan-number

loan left outer join borrower onloan.loan-number = borrower.loan-number

branch-name amount

Downtown

Redwood

3000

4000

customer-name

loan-number

Jones

Smith

L-170

L-230

loan-number

L-170

L-230

branch-name amount

Downtown

Redwood

Perryridge

3000

4000

1700

customer-name loan-number

Jones

Smith

null

L-170

L-230

null

loan-number

L-170

L-230

L-260

Page 60: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Joined Relations – ExamplesJoined Relations – Examples

loan loan natural inner joinnatural inner join borrowerborrower

loan natural right outer join borrower

branch-name amount

Downtown

Redwood

3000

4000

customer-name

Jones

Smith

loan-number

L-170

L-230

branch-name amount

Downtown

Redwood

null

3000

4000

null

customer-name

Jones

Smith

Hayes

loan-number

L-170

L-230

L-155

Page 61: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

Joined Relations – ExamplesJoined Relations – Examples loan loan full outer join full outer join borrower borrower

using using (loan-number)(loan-number)

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

branch-name amount

Downtown

Redwood

Perryridge

null

3000

4000

1700

null

customer-name

Jones

Smith

null

Hayes

loan-number

L-170

L-230

L-260

L-155

select customer-namefrom (depositor natural full outer join borrower)where account-number is null or loan-number is null

Page 62: Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested

End of ChapterEnd of Chapter