database system concepts · chapter 3: sql departamento de engenharia inform´atica instituto...
TRANSCRIPT
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Database System ConceptsChapter 3: SQL
Departamento de Engenharia InformaticaInstituto Superior Tecnico
1st Semester2008/2009
Slides (fortemente) baseados nos slides oficiais do livro“Database System Concepts”c©Silberschatz, Korth and Sudarshan.
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Outline
1 Data Definition Language
2 Querying the DatabaseBasic SQL QueriesAggregation and Set OperationsNull ValuesComplex Queries
3 Views
4 Modification of the Database
5 Joined Relations
6 Examples
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Outline
1 Data Definition Language
2 Querying the Database
3 Views
4 Modification of the Database
5 Joined Relations
6 Examples
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Data Definition Language
Allows the specification of not only a set of relations but alsoinformation about each relation, including:
The schema for each relation.
The domain of values associated with each attribute.
Integrity constraints
The set of indices to be maintained for each relations.
Security and authorization information for each relation.
The physical storage structure of each relation on disk.
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Domain Types in SQL
char(n) - Fixed length character string, with user-specifiedlength n.varchar(n) - Variable length character strings, withuser-specified maximum length n.int - Integer (a finite subset of the integers that ismachine-dependent).smallint - Small integer (a machine-dependent subset ofthe integer domain type).numeric(p,d) - Fixed point number, with user-specifiedprecision of p digits, with n digits to the right of decimalpoint.real, double - Floating point and double-precision floatingpoint numbers, with machine-dependent precision.float(n) - Floating point number, with user-specifiedprecision of at least n digits.More are covered in the book...
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Creating Tables
An SQL relation is defined using the create table
command:
create table r ((A1 D1,A2 D2, . . . ,An Dn)constraint1, . . . , constraintk
)
r is the name of the relationeach Ai is an attribute name in the schema of relation r
Di is the data type of values in the domain of attribute Ai
Example:
create table branch (branch name char(15),branch city char(30),assets integer )
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Integrity Constraints
Ensuring non-null values: not null
Defining the identifier: primary key (A1, . . . ,An)
Example:
create table branch (branch name char(15),branch city char(30),assets integer not null,primary key (branch name)
)
Note: primary key also ensures that the attribute is not null
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Deleting and Altering Tables
The drop table command deletes all information aboutthe dropped relation from the database.
drop table r
The alter table command is used to add/removeattributes to/from an existing relation:
alter table r add A D
alter table r drop A
where A is the name of the attribute to be added torelation r and D is the domain of A.
All tuples in the relation are assigned null as the value forthe new attribute.Dropping of attributes is not supported by many databases
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Outline
1 Data Definition Language
2 Querying the DatabaseBasic SQL QueriesAggregation and Set OperationsNull ValuesComplex Queries
3 Views
4 Modification of the Database
5 Joined Relations
6 Examples
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Basic Query Structure
SQL is based on set and relational operations with certainmodifications and enhancements
A typical SQL query has the form:
select A1,A2, . . . ,An
from r1, r2, . . . , rmwhere P
Ai represents an attributeri represents a relationP is a predicate.
This query is equivalent to the relational algebra expression
πA1,A2,...,An
(
σP(r1 × r2 × · · · × rm))
The result of an SQL query is a relation
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
The select Clause
The select clause list the attributes desired in the result ofa query
Corresponds to the projection operation of the relationalalgebra
Example: find the names of all branches in the loanrelation:
select branch name
from loan
In the relational algebra, the query would be:
πbranch name(loan)
Note : SQL names are case insensitive (i.e., you may use upper- orlower-case letters.)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
The select Clause (cont.)
SQL allows duplicates in relations as well as in queryresults
To force the elimination of duplicates, insert the keyworddistinct after select
Example: find the names of all branches in the loanrelations, and remove duplicates
select distinct branch name
from loan
The keyword all specifies that duplicates not be removed
select all branch name
from loan
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
The select Clause (cont.)
An asterisk in the select clause denotes “all attributes”
select ∗from loan
The select clause can contain arithmetic expressionsinvolving the operation, +, −, ∗, and /, and operating onconstants or attributes of tuples
select loan number , branch name, amount ∗ 100from loan
would return a relation that is the same as the loan relation,except that the value of the attribute amount is multiplied by100.
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
The where Clause
The where clause specifies conditions that the result mustsatisfy
Corresponds to the selection predicate of the relationalalgebra
Example: to find all loan number for loans made at thePerryridge branch with loan amounts greater than $1200
select loan number
from loan
where branch name = ’Perryridge’ and amount > 1200
Comparison results can be combined using the logicalconnectives and, or, and not
Comparisons can be applied to results of arithmeticexpressions
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
The where Clause (cont.)
SQL includes a between comparison operator
Example: Find the loan number of those loans with loanamounts between $90 000 and $100 000 (that is,≥ $90 000 and ≤ $100 000)
select loan number
from loan
where amount between 90000 and 100000
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
The from Clause
The from clause lists the relations involved in the query
Corresponds to the Cartesian product operation of therelational algebra
Example: find the Cartesian product borrower × loan
select ∗from borrower , loan
Example: find the name, loan number and loan amount ofall customers having a loan at the Perryridge branch
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
The from Clause
The from clause lists the relations involved in the query
Corresponds to the Cartesian product operation of therelational algebra
Example: find the Cartesian product borrower × loan
select ∗from borrower , loan
Example: find the name, loan number and loan amount ofall customers having a loan at the Perryridge branch
loan(loan number , branch name, amount)borrower(customer name, loan number)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
The from Clause
The from clause lists the relations involved in the query
Corresponds to the Cartesian product operation of therelational algebra
Example: find the Cartesian product borrower × loan
select ∗from borrower , loan
Example: find the name, loan number and loan amount ofall customers having a loan at the Perryridge branch
select customer name, loan.loan number , amount
from loan, borrower
where loan.loan number = borrower .loan number
and branch name = ’Perryridge’
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Renaming
SQL allows renaming relations and attributes using the as
clause:
old-name as new-name
Example: find the name, loan number and loan amount ofall customers; rename the column loan number as loan id
select customer name, borrower .loan number as loan id ,amount
from borrower , loan
where borrower .loan number = loan.loan number
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Tuple Variables
Tuple variables are defined in the from clause via the useof the as clause.
Example: find the customer names and their loan numbersfor all customers having a loan
select customer name, B.loan number , L.amount
from borrower as B, loan as L
where B.loan number = L.loan number
Example: find the names of all branches that have greaterassets than some branch located in Brooklyn
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Tuple Variables
Tuple variables are defined in the from clause via the useof the as clause.
Example: find the customer names and their loan numbersfor all customers having a loan
select customer name, B.loan number , L.amount
from borrower as B, loan as L
where B.loan number = L.loan number
Example: find the names of all branches that have greaterassets than some branch located in Brooklyn
branch(branch name, branch city , assets)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Tuple Variables
Tuple variables are defined in the from clause via the useof the as clause.
Example: find the customer names and their loan numbersfor all customers having a loan
select customer name, B.loan number , L.amount
from borrower as B, loan as L
where B.loan number = L.loan number
Example: find the names of all branches that have greaterassets than some branch located in Brooklyn
select distinct T .branch name
from branch as T , branch as S
where T .assets > S .assets and S .branch city = ’Brooklyn’
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
String Operations
The operator like uses patterns that are described usingtwo special characters:
percent (%) - matches any substring.underscore ( ) - matches any character.
Example: find the names of all customers whose streetincludes the substring “Main”
select customer name
from customer
where customer street like ’%Main%’
To match the name “Main%”
like ’Main\%’ escape ’\’
SQL supports many other string operations
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Ordering the Display of Tuples
List in alphabetic order the names of all customers havinga loan in Perryridge branch
select distinct customer name
from borrower B, loan L
where B.loan number = L.loan number
and branch name = ’Perryridge’order by customer name
We may specify desc for descending order or asc forascending order (the default)
order by customer name desc
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Set Operations
Find all customers who have a loan, an account, or both
(select customer name from depositor)union(select customer name from borrower)
Find all customers who have both a loan and an account
(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)except(select customer name from borrower)
Each of the above operations automatically eliminates duplicates; to retain
all duplicates use the corresponding multiset versions: union all,
intersect all and except all
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Aggregate Functions
Operate on the multiset of values of a column of a relation, andreturn a value
avg, min, max, sum, count
Find the average account balance at the Perryridge branch
select avg(balance)from account
where branch name = ’Perryridge’
Find the number of tuples in the customer relation
select count(∗) from customer
Find the number of depositors in the bank
select count(distinct customer name)from depositor
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Aggregate Functions - group by
Find the number of depositors for each branch
select branch name, count(distinct customer name)from depositor , account
where depositor .account number = account.account number
group by branch name
Note: attributes in select clause outside of aggregate functionsmust appear in group by list
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Aggregate Functions - having
Find the names of all branches where the average accountbalance is more than $1 200
select branch name, avg(balance)from account
group by branch name
having avg(balance) > 1200
Note: predicates in the having clause are applied after the formation
of groups whereas predicates in the where clause are applied before
forming groups
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Null Values
It is possible for tuples to have the null value
The result of any arithmetic expression involving null isnull
Any comparison with null returns unknown
The predicates is null and is unknown can be used tocheck for null values and unknown results
select loan number
from loan
where amount is null
select loan number
from loan
where amount > 1000 is unknown
Note: result of where clause predicate is treated as false if itevaluates to unknown
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Null Values and Aggregates
Total all loan amounts
select sum(amount)from loan
Above statement ignores null amounts
Result is null if there is no non-null amount
All aggregate operations except count(∗) ignore tupleswith null values on the aggregated attributes.
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Nested Subqueries
A common use of nested subqueries is to perform tests forset membership, set comparisons, and set cardinality
Find all customers who have both an account and a loanat the bank
select distinct customer name
from borrower
where customer name in (select customer name
from depositor)
Find all customers who have a loan at the bank but do nothave an account at the bank
select distinct customer name
from borrower
where customer name not in (select customer name
from depositor)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Set Comparison
Find all branches that have greater assets than some branchlocated in Brooklyn
select branch name
from branch
where assets >some (select assets
from branch
where branch city = ’Brooklyn’)
>some, <some, =some, <>some
Find the names of all branches that have greater assets than allbranches located in Brooklyn
select branch name
from branch
where assets >all (select assets
from branch
where branch city = ’Brooklyn’)
>all, <all, =all, <>all
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Test for Empty Relations
The exists construct returns the value true if theargument subquery is nonempty
exists r ⇔ r 6= ∅
Example: find all customers who do not have an accountat the Perryridge branch
select D.customer name
from depositor D
where not exists (select T .customer name
from account A, depositor T
where D.customer name = T .customer name andT .account number = A.account number andA.branch name = ’Perryridge’)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Division
Find all customers who have an account at all brancheslocated in Brooklyn
select distinct S .customer name
from depositor S
where not exists ((select branch name
from branch
where branch city = ’Brooklyn’)except(select R.branch name
from depositor T , account R
where T .account number = R.account number andS .customer name = T .customer name ))
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Division
Find all customers who have an account at all brancheslocated in Brooklyn
select distinct S .customer name
from depositor S
where not exists ((select branch name
from branch
where branch city = ’Brooklyn’)except(select R.branch name
from depositor T , account R
where T .account number = R.account number andS .customer name = T .customer name ))
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Test for Absence of Duplicate Tuples
The unique construct tests whether a subquery has anyduplicate tuples in its result
Example: find all customers who have at most oneaccount at the Perryridge branch
select D.customer name
from depositor D
where unique (select T .customer name
from account A, depositor T
where D.customer name = T .customer name andT .account number = A.account number andA.branch name = ’Perryridge’)
What about all customers who have at least two accountsat the Perryridge branch?
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
Derived Relations
SQL allows a subquery expression to be used in the fromclause
Find the average account balance of those branches wherethe 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
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Basic SQLQueries
Aggregation andSet Operations
Null Values
Complex Queries
Views
Modificationof theDatabase
JoinedRelations
Examples
The with Clause
The with clause provides a way of defining a temporaryview whose definition is available only to the query inwhich the with clause occurs
Example: find all accounts with the maximum balance
with max balance(value) asselect max(balance)from account
select account number
from account, max balance
where account.balance = max balance.value
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Outline
1 Data Definition Language
2 Querying the Database
3 Views
4 Modification of the Database
5 Joined Relations
6 Examples
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Views
In some cases, it is not desirable for all users to see theentire logical model
Consider a person who needs to know a customer’s loannumber but has no need to see the loan amount
select customer name, loan number
from borrower , loan
where borrower .loan number = loan.loan number
A view provides a mechanism to hide certain data fromthe view of certain users.
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
View Definition
A view is defined using the create view statement whichhas 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 referto the virtual relation that the view generates.
View definition is not the same as creating a new relationby evaluating the query expressionRather, a view definition causes the saving of anexpression; the expression is substituted into queries usingthe view.
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
View Examples
A view consisting of branches and their customers
create view all customer as(select branch name, customer name
from depositor D, account A
where D.account number = A.account number)union
(select branch name, customer name
from borrower B, loan L
where B.loan number = L.loan number)
Find all customers of the Perryridge branch
select customer name
from all customer
where branch name = ’Perryridge’
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Outline
1 Data Definition Language
2 Querying the Database
3 Views
4 Modification of the Database
5 Joined Relations
6 Examples
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Deleting Tuples
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 from account
where branch name in (select branch name
from branch
where branch city = ’Needham’)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Insertion
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’)
Add a new tuple to account with balance set to null
insert into account
values (’A-777’, ’Perryridge’, null)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Insertion (cont.)
Provide as a gift for all loan customers of the Perryridgebranch, a $200 savings account. Let the loan numberserve as the account number for the new savings account
insert into account
select loan number , branch name, 200from loan
where branch name = ’Perryridge’
insert into depositor
select customer name, loan number
from loan, borrower
where branch name = ’Perryridge’ andloan.account number = borrower .account number
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Updates
Increase all accounts with balances over $10,000 by 6%,all other accounts receive 5%
update account
set balance = balance ∗ 1.06where balance > 10000
update accountset balance = balance ∗ 1.05where balance <= 10000
update accountset balance =
casewhen balance <= 10000 then balance ∗ 1.05else balance ∗ 1.06
end
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Updates
Increase all accounts with balances over $10,000 by 6%,all other accounts receive 5%
update account
set balance = balance ∗ 1.06where balance > 10000
update accountset balance = balance ∗ 1.05where balance <= 10000
update accountset balance =
casewhen balance <= 10000 then balance ∗ 1.05else balance ∗ 1.06
end
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Update of a View
Create a view of all loan data in the loan relation, hidingthe amount attribute
create view branch loan asselect branch name, loan number
from 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 thetuple
(’L-307’, ’Perryridge’, null)
into the loan relation
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Update of a View (cont.)
Some updates through views are impossible to translateinto updates on the database relations
create view avg bal asselect branch name, avg(balance)from account
group by branch name
insert into avg bal
values (’Downtown’, 300)
Most SQL implementations allow updates only on simpleviews (without aggregates) defined on a single relation
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Outline
1 Data Definition Language
2 Querying the Database
3 Views
4 Modification of the Database
5 Joined Relations
6 Examples
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Join Operations
Join types
inner join
left outer join
right outer join
full outer join
Join conditions
natural
on <predicate>
using (A1, A2, . . . ,An)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Join Operations (cont.)
loan
loan number branch name amount
L-170 Downtown 3000L-230 Redwood 4000L-260 Perryridge 1700
borrower
customer name loan number
Jones L-170Smith L-230Hayes L-155
select ∗ fromloan inner join borrower
on loan.loan number = borrower .loan number
loan number branch name amount customer name loan number
L-170 Downtown 3000 Jones L-170L-230 Redwood 4000 Smith L-170
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Join Operations (cont.)
loan
loan number branch name amount
L-170 Downtown 3000L-230 Redwood 4000L-260 Perryridge 1700
borrower
customer name loan number
Jones L-170Smith L-230Hayes L-155
select ∗ fromloan natural join borrower
loan number branch name amount customer name
L-170 Downtown 3000 JonesL-230 Redwood 4000 Smith
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Join Operations (cont.)
loan
loan number branch name amount
L-170 Downtown 3000L-230 Redwood 4000L-260 Perryridge 1700
borrower
customer name loan number
Jones L-170Smith L-230Hayes L-155
select ∗ fromloan left outer join borrower
on loan.loan number = borrower .loan number
loan number branch name amount customer name loan number
L-170 Downtown 3000 Jones L-170L-230 Redwood 4000 Smith L-230L-260 Perryridge 1700 null null
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Join Operations (cont.)
loan
loan number branch name amount
L-170 Downtown 3000L-230 Redwood 4000L-260 Perryridge 1700
borrower
customer name loan number
Jones L-170Smith L-230Hayes L-155
select ∗ fromloan natural right outer join borrower
loan number branch name amount customer name
L-170 Downtown 3000 JonesL-230 Redwood 4000 SmithL-155 null null Hayes
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Join Operations (cont.)
loan
loan number branch name amount
L-170 Downtown 3000L-230 Redwood 4000L-260 Perryridge 1700
borrower
customer name loan number
Jones L-170Smith L-230Hayes L-155
select ∗ fromloan full outer join borrower using(loan number)
loan number branch name amount customer name
L-170 Downtown 3000 JonesL-230 Redwood 4000 SmithL-260 Perryridge 1700 nullL-155 null null Hayes
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Outline
1 Data Definition Language
2 Querying the Database
3 Views
4 Modification of the Database
5 Joined Relations
6 Examples
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get data from all customers
account(account number , branch name, balance)branch(branch name, branch city , assets)
customer(customer name, customer street, customer city)loan(loan number , branch name, amount)
depositor(customer name, account number)borrower(customer name, loan number)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get data from all customers
select ∗ from customer
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name and city of all customers with a loan
account(account number , branch name, balance)branch(branch name, branch city , assets)
customer(customer name, customer street, customer city)loan(loan number , branch name, amount)
depositor(customer name, account number)borrower(customer name, loan number)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name and city of all customers with a loan
select distinct c .customer name, customer city
from borrower b, customer c
where b.customer name = c .customer name
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name and city of all customers with a loan at thePerryridge branch
account(account number , branch name, balance)branch(branch name, branch city , assets)
customer(customer name, customer street, customer city)loan(loan number , branch name, amount)
depositor(customer name, account number)borrower(customer name, loan number)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name and city of all customers with a loan at thePerryridge branch
select distinct c .customer name, customer city
from borrower b, customer c, loan l
where b.customer name = c .customer name
and b.loan number = l .loan number
and branch name = ’Perryridge’
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the number of all accounts with a balance between $700and $900
account(account number , branch name, balance)branch(branch name, branch city , assets)
customer(customer name, customer street, customer city)loan(loan number , branch name, amount)
depositor(customer name, account number)borrower(customer name, loan number)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the number of all accounts with a balance between $700and $900
select account number
from account
where balance between 700 and 900
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name of all customers whose street name ends in ’Hill’
account(account number , branch name, balance)branch(branch name, branch city , assets)
customer(customer name, customer street, customer city)loan(loan number , branch name, amount)
depositor(customer name, account number)borrower(customer name, loan number)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name of all customers whose street name ends in ’Hill’
select customer name
from customer
where customer street like ’%Hill’
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name of all customers with both an account and a loanat the Perryridge branch
account(account number , branch name, balance)branch(branch name, branch city , assets)
customer(customer name, customer street, customer city)loan(loan number , branch name, amount)
depositor(customer name, account number)borrower(customer name, loan number)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name of all customers with both an account and a loanat the Perryridge branch
select distinct b.customer name
from borrower b, loan l , depositor d , account a
where b.loan number = l .loan number
and b.customer name = d .customer name
and d .account number = a.account number
and a.branch name = ’Perryridge’and l .branch name = ’Perryridge’
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name of all customers with an account at any branchwhere customer Hayes has an account
account(account number , branch name, balance)branch(branch name, branch city , assets)
customer(customer name, customer street, customer city)loan(loan number , branch name, amount)
depositor(customer name, account number)borrower(customer name, loan number)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name of all customers with an account at any branchwhere customer Hayes has an account
select distinct d .customer name
from depositor d , account a
where d .account number = a.account number
and branch name in(select branch name
from depositor d , account a
where d .account number = a.account number
and d .customer name = ’Hayes’)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name of all agencies with higher assets than allagencies in Brooklyn
account(account number , branch name, balance)branch(branch name, branch city , assets)
customer(customer name, customer street, customer city)loan(loan number , branch name, amount)
depositor(customer name, account number)borrower(customer name, loan number)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name of all agencies with higher assets than allagencies in Brooklyn
select branch name
from branch
where assets > all
(select assets
from branch
where branch city = ’Brooklyn’)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name of all clients with a loan at the Perryridge branch
account(account number , branch name, balance)branch(branch name, branch city , assets)
customer(customer name, customer street, customer city)loan(loan number , branch name, amount)
depositor(customer name, account number)borrower(customer name, loan number)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name of all clients with a loan at the Perryridge branch
select distinct customer name
from borrower b, loan l
where b.loan number = l .loan number
and l .branch name = ’Perryridge’order by b.customer name
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name and number of customers of all agencies
account(account number , branch name, balance)branch(branch name, branch city , assets)
customer(customer name, customer street, customer city)loan(loan number , branch name, amount)
depositor(customer name, account number)borrower(customer name, loan number)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name and number of customers of all agencies
select branch name, count(distinct customer name)from depositord , accounta
where d .account number = a.account number
group by branch name
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name and average balance of all agencies with anaverage balance above $700
account(account number , branch name, balance)branch(branch name, branch city , assets)
customer(customer name, customer street, customer city)loan(loan number , branch name, amount)
depositor(customer name, account number)borrower(customer name, loan number)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name and average balance of all agencies with anaverage balance above $700
select branch name, avg(balance)from account
group by branch name
having avg(balance) > 700
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name of the agencies with the highest average balance
account(account number , branch name, balance)branch(branch name, branch city , assets)
customer(customer name, customer street, customer city)loan(loan number , branch name, amount)
depositor(customer name, account number)borrower(customer name, loan number)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the name of the agencies with the highest average balance
select branch name
from account
group by branch name
having avg(balance) >= all(select avg(balance)from account
group by branch name)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the total number of customers in the database
account(account number , branch name, balance)branch(branch name, branch city , assets)
customer(customer name, customer street, customer city)loan(loan number , branch name, amount)
depositor(customer name, account number)borrower(customer name, loan number)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get the total number of customers in the database
select count(∗) from customer
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get average balance of all customers who live in Harrison andhave, at least, two bank accounts
account(account number , branch name, balance)branch(branch name, branch city , assets)
customer(customer name, customer street, customer city)loan(loan number , branch name, amount)
depositor(customer name, account number)borrower(customer name, loan number)
DatabaseSystem
Concepts
DataDefinitionLanguage
Querying theDatabase
Views
Modificationof theDatabase
JoinedRelations
Examples
Example Queries
Get average balance of all customers who live in Harrison andhave, at least, two bank accounts
select avg(balance)from depositor d , account a, customer c
where d .customer name = c .customer name
and d .account number = a.account number
and customer city = ’Harrison’group by d .customer name
having count(distinct a.account number) >= 2