Vous êtes sur la page 1sur 16

Oracle 10g Compatible SQL Expressions

3.3.1 The select Clause


a) Find the names of all branches in the loan relation.
select branch_name from loan
select distinct branch_name form loan
select all branch_name form loan

The asterisk * symbol can be used to denote all attributes


select * from loan

The select clause may also contain arithmetic expressions involving the
operators +, -, * and / operating on constants or attributes of tuples.
[Generalized projection in relational algebra]
select loan_no, amount * 100 from loan

3.3.2 The where Clause


a) Find all loan numbers for loans made at the Perryridge branch with loan
amounts greater than 300.
select *
from loan
where branch_name=Perryridge and amount > 300

SQL uses the logical connectives and, or and not. The operands of the
logical connectives can be expressions involving the comparison operators <,
<=, >, >=, = and <>. SQL allows us to use comparison operators to compare
strings and arithmetic expressions as well as special types such as dates.

SQL includes a between comparison to simplify where clause that specify <=
and >=. It is also possible to use not between operators.

b) Find the loan number of those loans with loan amounts between 400 and 800.
select loan_no
from loan
where amount between 400 and 800

or
select loan_number
from loan
where amount >= 400 and amount <=800

3.3.3 The from Clause


a) For all customers who have a loan from the bank, find their names, loan
numbers and loan amount.
select customer_name, loan.loan_number, amount
from borrower, loan
where loan.loan_no = borrower.loan_no

3.3.4 The Rename Operation


select customer_name, loan.loan_no as loan_id, amount
from borrower, loan
where loan.loan_no = borrower.loan_no

3.3.5 Tuple Variables


a) Find all customers who have a loan from the bank, find their names, loan
numbers and loan amount.
select customer_name, L.loan_number, amount
from borrower B, loan L
where L.loan_no = B.loan_no
b) Find the names of all branches that have assets greater than at least one
branch located in Horseneck.
select distinct T.branch_name
from branch T, branch S
where T.assets > S.assets and S.branch_city = Horseneck
or
select distinct S.branch_name
from branch T, branch S
where S.assets > T.assets and T.branch_city = Horseneck

3.3.6 String Operation


SQL specifies strings by enclosing them in single quotes, for example Mirpur. To
represent its ok we use its ok
1. Pattern matching operation is done using operator like with two special
characters. Patterns are case sensitive.
i) Percent (%) matches any substring
ii) Underscore (_) matches any character
Examples:
a) Mir% Mirpur, Mirzafar
b) %gla% Bangladesh, Bangla Motor
c) Book% Book Store, Book Fair, Booking
d) _ _ _ any string of exactly three characters
e) _ _ _ % any string of at least three characters
a) Find the names of all customers whose street address includes the substring
Main.
select customer_name
from customer
where customer_street like %Main%
2. The escape {backslash ( \ )} character is used immediately before a special
pattern character to indicate that it is to be treated like a normal character.
i) like ab\%cd% escape \ matches all strings beginning with ab%cd%
ii) like ab\\cd% escape \ matches all strings beginning with ab\cd%
iii) like ab\?cd% escape \ matches all strings beginning with ab?cd%
SQL allows not like for searching mismatches.
3. SQL permits a variety of functions on character strings:
a) concatenating (using ||) - [ Computer || || Science] Computer Science
b) extracting substrings - substr(Computer, 4, 5) puter
c) finding length of string - LENGTH(Computer) 8
d) conversion between uppercase and lowercase UPPER(char), Lower(char)

3.3.7 Ordering the Display of Tuples


a) Find the list of all customers in alphabetic order who have a loan in the
Perryridge branch.
select distinct customer_name
from borrower B, loan L
where L.loan_no = B.loan_no and branch_name = Perryridge
order by customer_name
select * from loan
order by amount desc, loan_no asc

3.4 Set Operations


Comparison:
SQL

union

intersect

except/minus

3.4.1 The Union Operation


a) Find all customers having a loan, an account or both at the bank.
(select customer_name from depositor)
union
(select customer_name from borrower)

Unlike the select clause, the union operation automatically eliminates


duplicates. If we want to retain all duplicates:

(select customer_name from depositor)


union all
(select customer_name from borrower)

3.4.2 The Intersect Operation


a) Find all customers who have both a loan and an account at the bank.
(select customer_name from depositor)
intersect
(select customer_name from borrower)

The intersect operation automatically eliminates duplicates. If we want to


retain all duplicates: (oracle does not support)

(select customer_name from depositor)


intersect all
(select customer_name from borrower)

3.4.3 The Except Operation (Minus)


a) Find all customers who have an account but no loan at the bank.
(select customer_name from depositor)
minus
(select customer_name from borrower)

The except operation automatically eliminates duplicates. If we want to retain


all duplicates: (oracle does not support)

(select customer_name from depositor)


minus all
(select customer_name from borrower)

3.5 Aggregate Functions

Aggregate functions are functions that take a collection (a set or multiset) of


values as input and return a single value. SQL offers five built-in aggregate
functions:

1. Average: avg
2. Minimum: min
3. Maximum: max
4. Total: sum
5. Count: count

The input to sum and avg must be a collection of numbers, but the other
operators can operate on collection of non-numeric data types, such as string,
as well.

Aggregate functions on a single set of tuples:

a) Find the average account balance.


select avg(balance)
from account

b) Find the total account balance of Perryridge branch.


select sum(balance)
from account
where branch_name = Perryridge

Aggregate functions on a group of sets of tuples:

c) Find the average account balance, maximum account balance at each branch.
select branch_name, avg(balance), max(balance)
from account
group by branch_name

Retaining duplicates is important in computing sum or average. There are


some cases where we must eliminate duplicate before computing an
aggregate function.

d) Find numbers of depositors for each branch.


select branch_name, count(distinct customer_name)
from depositor D, account A
where D.account_no = A. account_no
group by branch_name

At times it is useful to state a condition that applies to groups rather than to


tuples.

e) Find branch name and average balance where average balance is greater
than 400.
select branch_name, avg(balance)
from account
group by branch_name
having avg(balance) > 1200
f) Find branch name and average balance of Mirpur, Firmgate or Dhanmonidi
branch where average balance is greater than 1200.
select branch_name, avg(balance)
from account
where branch_name in (Mirpur, Firmgate, Dhanmondi)
group by branch_name
having avg(balance) > 1200
or

select branch_name, avg(balance)


from account
group by branch_name
having branch_name in (Mirpur, Firmgate, Dhanmondi) and avg(balance) >
1200

At times, we wish to treat the entire relation as a single group. In such cases,
group by is not used.

g) Find the minimum loan amount.


select min(amount) from loan

The aggregate function count is frequently used to count the number of


tuples in a relation.

h) Count the number of tuples in customer relation.


select count(*) from customer

SQL does not allow the use of distinct with count(*). distinct can be used
with min and max, but result does not change.

i) Find the average balance for each customer who lives in Dhaka and has at
least three accounts.
select D.customer_name, avg(balance)
from account A, depositor D, customer C
where
A.account_no.
=
D.account_no.
C.customer_name and customer_city = Dhaka
group by D.customer_name
having count(distinct D.account_no) >=3

and

D.customer_name

3.6 Null Values


a) Find all loan numbers which appear in the loan relation with null values for
amount.
select loan_number
from loan
where amount is null

The use of a null value in arithmetic and comparison operations causes


several complications. The result of any arithmetic expression involving null

returns null. So 5 + null returns null. Any comparison with null returns
unknown (other than is null and is not null). So, 5 < null or null <> null or null
= null returns unknown.
select sum(amount)
from loan
ignores null amount. Result is null if there is no non-null amount.

All aggregate functions except count(*) ignore tuple with null values on the
aggregated attributes.

3.7 Nested Subqueries

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


query. A common use of subqueries is to i) perform tests for set membership,
ii) make set comparisons and iii) determine set cardinality.

3.7.1 Set Membership

The in connective tests for set membership, where the set is a collection of
values produced by a select clause. The not in connective tests for the
absence of the set membership.

Membership in a one-attribute relation:


a) Find all customers who have both a loan and an account at the bank.
select distinct customer_name
from borrower
where customer_name in (select customer_name from depositor)
or
select distinct customer_name
from depositor
where customer_name in (select customer_name from borrower)
There is substantial amount of redundancy in SQL.
Membership in an arbitrary relation:
b) Find all customers who have both a loan and an account at Perryridge branch.
select distinct customer_name

from borrower b, loan l


where b.loan_number = l.loan_number and branch_name = Perryridge and
(branch_name, customer_name) in (select branch_name, customer_name
from depositor d, account a
where d.account_no = a.account_no))
alternately intersect will do:
(select customer_name
from borrower b, loan l
where b.loan_no = l.loan_no and branch_name = Perryridge)
intersect
(select customer_name
from depositor d, account a
where d.account_no = a.account_no and branch_name = Perryridge)
c) Find all customers who have a loan but no account at the bank.
select distinct customer_name
from borrower
where customer_name not in (select customer_name from depositor)
d) Find all customers who have an account but no loan at the bank.
select customer_name
from depositor
where customer_name not in (select customer_name from borrower)

The in and not in can also be used on enumerated sets.

d) Find all customers who have a loan at the bank and whose names are neither
Rahim nor karim.
select distinct customer_name
from borrower
where customer_name not in (Rahim, Karim)

3.7.2 Set Comparison


a) Find the names of all branches that have assets greater than at least one
branch located in Brooklyn.
select distinct T.branch_name
from branch T, branch S

where T.assets > S.assets and S.branch_city = Brooklyn


or
select distinct S.branch_name
from branch T, branch S
where S.assets > T.assets and T.branch_city = Brooklyn

The phrase greater than at least one is represented in SQL by > some

select branch_name
from branch
where assets > some (select assets
from branch
where branch_city = Brooklyn)

SQL also allows < some, <= some, >= some, = some and <> some
comparisons. Note that, = some is identical to in, whereas <> some is not
the same as not in.

The construct > all corresponds to the phrase greater than all.

b) Find the names of all branches that have an asset value greater than that of
each branch located in Brooklyn
select branch_name
from branch
where assets > all (select assets
from branch
where branch_city = Brooklyn)

SQL also allows < all, <= all, >= all, = all and <> all comparisons. Note that,
<> all is identical to not in.

Aggregate functions cannot be composed in SQL. Thus, we cannot use


max (avg ()) ???
c) Find the branch that has 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)
-------------------

create view avg_bal as


select branch_name, avg(balance) avg_bal
from account
group by branch_name
create view max_bal as
select max(avg_bal) max_bal
from avg_bal
select branch_name
from avg_bal, max_bal
where avg_bal = max_bal
---------------------create view avg_bal as
select branch_name, avg(balance) avg_bal
from account
group by branch_name
select branch_name
from avg_bal
where avg_bal = ( select max(avg_bal)
from avg_bal)

3.7.3 Test for Empty Relations


a) Find all customers who have both a loan and an account at the bank.
select distinct b.customer_name
from borrower b
where exists (select *
from depositor d
where d.customer_name = b.customer_name)
b) Find all customers who have a loan, but no account at the bank.
select distinct b.customer_name
from borrower b
where not exists (select *
from depositor d
where d.customer_name = b.customer_name)

3.7.4 Test for the Absence of Duplicate Tuples


a) Find all customers who have at most one account at Mirpur branch.
select d1.customer_name
from depositor d1
where unique (select d2.customer_name
from account a, depositor d2
where d1.customer_name = d2.customer_name and
a.account_number = d2.account_number and
a.branch_name = Mirpur)
a) Find all customers who have at least two accounts at Mirpur branch.
select d1.customer_name
from depositor d1
where not unique (select d2.customer_name
from account a, depositor d2
where d1.customer_name = d2.customer_name and
a.account_number = d2.account_number and
a.branch_name = Mirpur)

3.8.1 Derived Relations


a) Find the average account balance of those branches where the average
account balance is greater than 400.
select branch_name, avg_balance
from (select branch_name, avg(balance) avg_balance
from account
group by branch_name)
where avg_balance > 400
Using having clause:
select branch_name, avg(balance) avg_balance
from account
group by branch_name
having avg(balance) > 400
b) Find the maximum across all branches of the total balance at each branch.
select branch_name, max(tot_balance) max_balance
from (select branch_name, sum(balance) tot_balance

from account
group by branch_name)

Using having clause:

select branch_name, sum(balance) as max_balance


from account
group by branch_name
having sum(balance) >= all (select sum(balance)
from account
group by branch_name)

3.8.2 The With Clause


a) Find the account with maximum balance.
// Using Cartesian product
with max_balance as
(select max (balance) max_balance
from account)
select account_no, max_balance
from account a, max_balance m
where a.balance = m.max_balance
// Using Natural Join
with max_balance as
(select max (balance) balance
from account)
select account_no, balance
from account natural Join max_balance
b) Find all branches where the total account deposit is less than the average of
the total account deposits at all branches.
with branch_total as
(select branch_name, sum (balance) sum_bal
from account
group by branch_name),
branch_total_avg as
(select avg(sum_bal) avg_bal
from branch_total)
select branch_name, sum_bal, avg_bal
from branch_total a, branch_total_avg b
where a.sum_bal < b.avg_bal

3.9 Views
a) Create a view consisting of branch names and the names of customers who
have either an account or loan at the bank.
create view all_customers as
(select branch_name, customer_name
from depositor d, account a
where d.account_no = a.account_no )
union
(select branch_name, customer_name
from borrower b, loan l
where b.loan_no = l.loan_no )

The attribute names of a view can be specified explicitly as follows:

create view branch_total_loan(branch_name, total_loan) as


(select branch_name, sum(amount)
from loan
group by branch_name)
c) Using view all_customers, find all customers of Mirpur branch.
select customer_name
from all_customers
where branch_name = Perryridge

3.10 Modification of the Database


3.10.1 Deletion
a) Delete all of Smith's account records
delete from depositor
where customer_name=Smith
b) Delete all account tuples in the Perryridge branch
delete from account
where branch_name=Perryridge

c) Delete all loans with loan amounts between 1300 and 1500.
delete from loan
where amount between 1300 and 1500
d) Delete all accounts at branches located in Brooklyn
delete from account
where branch_name in
(select branch_name
from branch
where branch_city = Brooklyn)
e) Delete the records of all accounts with balances below the average
delete from account
where balance < (select avg(balance)
from account)

3.10.3 Updates
a) Increase all balances by 5 percent.
update account
set balance = balance * 1.05
b) Give 6 percent interest for all accounts with balance over 700 and 5 percent
for the rest.
update account
set balance = balance * 1.06
where balance > 700
update account
set balance = balance * 1.05
where balance <= 700
Using case:
update account
set balance = case
when balance <= 700 then balance * 1.05
else balance * 1.06
end

c) Pay 5% interest on account whose balance is greater than average


update account
set balance = balance * 1.05
where balance > (select avg (balance)
from account)
Queries:
1. Find all customers who have an account but no loan at the bank.
select d.customer_name
from (depositor d left outer join borrower b
on d.customer_name = b.customer_name)
where b.customer_name is null
(select customer_name from depositor)
minus
(select customer_name from borrower)
2. Find all customers who have either an account or a loan (but not both) at the
bank.
select customer_name
from (depositor natural full outer join borrower)
where account_no is null or loan_no is null
((select customer_name from depositor
union
select customer_name from borrower)
minus
(select customer_name from depositor
intersect
select customer_name from borrower))

Vous aimerez peut-être aussi