0% found this document useful (0 votes)
9 views35 pages

CH 4

Chapter 4 covers SQL fundamentals including basic structure, set operations, aggregate functions, and joins. It explains SQL query components such as SELECT, FROM, WHERE clauses, and introduces concepts like views and data modification. Additionally, it discusses string operations, ordering results, and the use of aggregate functions with GROUP BY and HAVING clauses.

Uploaded by

Sushma Borkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views35 pages

CH 4

Chapter 4 covers SQL fundamentals including basic structure, set operations, aggregate functions, and joins. It explains SQL query components such as SELECT, FROM, WHERE clauses, and introduces concepts like views and data modification. Additionally, it discusses string operations, ordering results, and the use of aggregate functions with GROUP BY and HAVING clauses.

Uploaded by

Sushma Borkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 35

Chapter 4: SQL

• Basic Structure
• Set Operations
• Aggregate Functions
• Null Values
• Nested Subqueries
• Derived Relations
• Views
• Modification of the Database
• Joined Relations
• Data Definition Language
• Embedded SQL, ODBC and JDBC
Schema Used in Examples
Basic Structure
• SQL is based on set and relational operations with
certain modifications and enhancements
• A typical SQL query has the form:
select A1, A2, ..., An
from r1, r2, ..., rm
where P
– Ais represent attributes
– ris represent relations
– P is a predicate.
• This query is equivalent to the relational algebra
expression.
A1, A2, ..., An(P (r1 x r2 x ... x rm))
• The result of an SQL query is a relation.
The select Clause
• The select clause list the attributes desired in the
result of a query
– corresponds to the projection operation of the relational algebra
• E.g. find the names of all branches in the loan
relation
select branch-name
from loan
• In the “pure” relational algebra syntax, the query
would be:
branch-name(loan)
• NOTE: SQL does not permit the ‘-’ character in
names,
– Use, e.g., branch_name instead of branch-name in a real implementation.
– We use ‘-’ since it looks nicer!
• NOTE: SQL names are case insensitive, i.e. you can
use capital or small letters.
– You may wish to use upper case where-ever we use bold font.
The select Clause (Cont.)
• SQL allows duplicates in relations as well as in query
results.
• To force the elimination of duplicates, insert the
keyword distinct after select.
• Find the names of all branches in the loan relations,
and remove duplicates
select distinct branch-name
from loan
• The keyword all specifies that duplicates not be
removed.
select all branch-name
from loan
The select Clause (Cont.)
• An asterisk in the select clause denotes “all attributes”
select *
from loan
• The select clause can contain arithmetic expressions
involving the operation, +, –, , and /, and operating on
constants or attributes of tuples.
• The query:
select loan-number, branch-name, amount
 100
from loan
would return a relation which is the same as the loan
relations, except that the attribute amount is multiplied by
100.
The where Clause
• The where clause specifies conditions that the result must
satisfy
– corresponds to the selection predicate of the relational algebra.
• To find all loan number for loans made at the Perryridge
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 logical
connectives and, or, and not.
• Comparisons can be applied to results of arithmetic
expressions.
The where Clause (Cont.)
• SQL includes a between comparison operator
• E.g. Find the loan number of those loans with
loan amounts between $90,000 and $100,000
(that is, $90,000 and $100,000)

select loan-number
from loan
where amount between 90000 and 100000
The from Clause
• The from clause lists the relations involved in the query
– corresponds to the Cartesian product operation of the relational algebra.

• Find the Cartesian product borrower x loan


select 
from borrower, 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, amount


from borrower, loan
where borrower.loan-number = loan.loan-number and
branch-name = ‘Perryridge’
The Rename Operation
• The SQL allows renaming relations and attributes using the as
clause:
old-name as new-name

• Find the name, loan number and loan amount of all customers;
rename the column name 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
Tuple Variables
• 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.
select customer-name, T.loan-number, S.amount
from borrower as T, loan as S
where T.loan-number = S.loan-number
 Find the names of all branches that have greater assets 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’
String Operations
• SQL includes a string-matching operator for comparisons on character strings.
Patterns are described using two special characters:
– percent (%). The % character matches any substring.
– underscore (_). The _ character matches any character.
• Find the names of all customers whose street includes the substring “Main”.
select customer-name
from customer
where customer-street like ‘%Main%’
• Match the name “Main%”
like ‘Main\%’ escape ‘\’
• SQL supports a variety of string operations such as
– concatenation (using “||”)
– converting from upper to lower case (and vice versa)
– finding string length, extracting substrings, etc.
Ordering the Display of Tuples
• List in alphabetic order the names of all customers
having a loan in Perryridge branch
select distinct customer-name
from borrower, loan
where borrower loan-number = loan.loan-
number and
branch-name = ‘Perryridge’
order by customer-name
• We may specify desc for descending order or asc for
ascending order, for each attribute; ascending order
is the default.
– E.g. order by customer-name desc
Duplicates
• In relations with duplicates, SQL can define how
many copies of tuples appear in the result.

• Example: Suppose multiset relations r1 (A, B) and


r2 (C) are as follows:
r1 = {(1, a) (2,a)} r2 = {(2), (3), (3)}
• SQL duplicate semantics:
select A1,, A2, ..., An
from r1, r2, ..., rm
where P
Set Operations
• The set operations union, intersect, and except
operate on relations and correspond to the relational
algebra operations 
• Each of the above operations automatically eliminates
duplicates; to retain all duplicates use the
corresponding multiset versions union all, intersect all
and except all.
Suppose a tuple occurs m times in r and n times in s,
then, it occurs:
– m + n times in r union all s
– min(m,n) times in r intersect all s
– max(0, m – n) times in r except all s
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)
Aggregate Functions
• These functions operate on the multiset of
values of a column of a relation, and return a
value
avg: average value
min: minimum value
max: maximum value
sum: sum of values
count: number of values
Aggregate Functions (Cont.)
• 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
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 functions must

appear in group by list


Aggregate Functions – Having Clause
• Find the names of all branches where the average
account balance 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
Views
• Provide a mechanism to hide certain data from the
view of certain users. To create a view we use the
command:
create view v as <query expression>

where:
<query expression> is any legal expression
The view name is represented by v
Example Queries
• A view consisting of branches and their customers
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)
 Find all customers of the Perryridge branch

select customer-name
from all-customer
where branch-name = ‘Perryridge’
Joined Relations
• Join operations take two relations and return as a result
another relation.
• These additional operations are typically used as
subquery expressions in the from clause
• Join condition – defines which tuples in the two
relations match, and what attributes are present in the
result of the join.
• Join type – defines how tuples in each relation that do
not match any tuple in the other relation (based on the
join condition) are treated.
Join Types Join Conditions
inner join natural
left outer join on <predicate>
right outer join using (A1, A2, ..., An)
full outer join
Joined Relations – Datasets for Examples
• Relation loan
loan-number branch-name amount

L-170 Downtown 3000


L-230 Redwood 4000
L-260 Perryridge 1700
 Relation borrower

customer-name loan-number

Jones L-170
Smith L-230
Hayes L-155
 Note: borrower information missing for L-260 and loan
information missing for L-155
Joined Relations – Examples
• loan 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-170


L-230 Redwood 4000 Smith L-230

 loan 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-170


L-230 Redwood 4000 Smith L-230
L-260 Perryridge 1700 null null
Joined Relations – Examples
• loan natural inner join borrower
loan-number branch-name amount customer-name

L-170 Downtown 3000 Jones


L-230 Redwood 4000 Smith

 loan natural right outer join borrower

loan-number branch-name amount customer-name

L-170 Downtown 3000 Jones


L-230 Redwood 4000 Smith
L-155 null null Hayes
Joined Relations – Examples
• loan full outer join borrower using (loan-number)

loan-number branch-name amount customer-name

L-170 Downtown 3000 Jones


L-230 Redwood 4000 Smith
L-260 Perryridge 1700 null
L-155 null null Hayes

 Find all customers who have either an account or a loan (but


not both) at the bank.

select customer-name
from (depositor natural full outer join borrower)
where account-number is null or loan-number is null
The loan and borrower Relations
The Result of loan inner join borrower
on loan.loan-number =
borrower.loan-number
The Result of loan left outer join
borrower on loan-number
The Result of loan natural inner join
borrower
Join Types and Join Conditions
The Result of loan natural right outer
join borrower
The Result of loan full outer join
borrower using(loan-number)
SQL Data Definition for Part of the Bank Database

You might also like