Comp 5311 Database Management Systems: 3. Structured Query Language 1
Comp 5311 Database Management Systems: 3. Structured Query Language 1
Comp 5311 Database Management Systems: 3. Structured Query Language 1
1
Aspects of SQL
3
Projection
• The select clause corresponds to the projection operation of the relational
algebra. It is used to list the attributes desired in the result of a query.
• Find the names of all branches in the loan relation
select branch-name
from loan
Equivalent to: branch-name(loan)
4
Duplicate Removal
5
Arithmetic Operations on Retrieved Results
6
The where Clause
7
The where Clause (Cont.)
8
The from Clause
• The from clause corresponds to the Cartesian product
operation of the relational algebra.
• Find the Cartesian product borrower loan
select *
from borrower, loan
It is rarely used without a where clause.
• Find the name and loan number of all customers
having a loan at the Perryridge branch.
select distinct customer-name, borrower.loan-number
from borrower, loan
where borrower.loan-number = loan.loan-number and
branch-name = “Perryridge”
9
The Rename Operation
10
Tuple Variables/Alias
• Tuple variables are defined in the from clause via the use of the
“as” clause.
• Find the customer names and their loan numbers for all customers
having a loan at some branch.
11
Tuple Variables/Alias
• Find the names of all branches that have greater assets than
some branch located in Brooklyn.
13
Ordering the Display of Tuples
15
Set operations
16
SQL - Nested Subqueries
select * select *
from loan from loan
where amount > 1200 where amount > select avg(amount)
from loan
• Illegal if the subquery returns the wrong type for the comparison
17
Example Query - IN
18
Example Query – NOT IN
19
The Some Clause
select branch-name
from branch
where assets > some
(select assets
from branch
where branch-city = “Brooklyn”)
20
Some Semantics
0
(5 < some 5 ) returns true (5 < 6)
6
21
The All Clause
• Find the names of all branches that have greater assets than all
branches located in Brooklyn.
– Equivalent to “find all branches that have greater assets than the
maximum assets of any branch located in Brooklyn”
select branch-name
from branch
where assets > all
(select assets
from branch
where branch-city=“Brooklyn”)
22
All Semantics
0
(5 < all 5 ) = false
6
23
Test for Empty Relations
• exists returns true if the argument subquery is nonempty.
• Find all customer names who have both a loan and an account.
24
Test for Absence of Duplicate Tuples
• unique tests whether a subquery has any duplicate tuples in its result.
• Find all customers who have only one account at the Perryridge branch.
25
Example Query – NOT UNIQUE
select T.customer-name
from depositor as T
where not unique(
select R.customer-name
from account, depositor as R
where T.customer-name = R.customer-name and
R.account-number = account.account-number and
account.branch-name = “Perryridge”)
26
Division in SQL
27