Chapter 3: SQL
Chapter 3: SQL
Chapter 3: SQL
Chapter 3: SQL
I Data Definition I Basic Query Structure I Set Operations I Aggregate Functions I Null Values I Nested Subqueries I Complex Queries I Views I Modification of the Database I Joined Relations**
3.<number>
History
I IBM Sequel language developed as part of System R project at the
I Renamed Structured Query Language (SQL) I ANSI and ISO standard SQL:
G G G G G
SQL-86 SQL-89 SQL-92 SQL:1999 (language name became Y2K compliant!) SQL:2003
varying feature sets from later standards and special proprietary features.
G
3.<number>
3.<number>
length n.
I int. Integer (a finite subset of the integers that is machine-dependent). I smallint. Small integer (a machine-dependent subset of the integer
domain type).
I float(n). Floating point number, with user-specified precision of at least n I More are covered in Chapter 4.
3.<number>
create table r (A1 D1, A2 D2, ..., An Dn, (integrity-constraint1), ..., (integrity-constraintk))
r is the name of the relation G each Ai is an attribute name in the schema of relation r
G G
I Example:
create table branch (branch_name char(15) not null, branch_city char(30), assets integer)
3.<number>
Example: Declare branch_name as the primary key for branch . create table branch (branch_name char(15), branch_city char(30), assets integer, primary key (branch_name))
primary key declaration on an attribute automatically ensures not null in SQL-92 onwards, needs to be explicitly stated in SQL-89
Database System Concepts, 5th Ed., June 2006 3.<number> Silberschatz, Korth and Sudarshan
alter table r add A D where A is the name of the attribute to be added to relation r and D is the domain of A.
G
All tuples in the relation are assigned null as the value for the new attribute.
relation:
3.<number>
A ,A ,,A ( P (r1 r2 rm ))
1 2 n
3.<number>
corresponds to the projection operation of the relational algebra select branch_name from loan branch_name (loan)
I In the relational algebra, the query would be: I NOTE: SQL names are case insensitive (i.e., you may use upper- or
lower-case letters.)
G G
E.g. Branch_Name
BRANCH_NAME
branch_name
3.<number>
select.
I Find the names of all branches in the loan relations, and remove
duplicates
3.<number>
operation, +, , , and /, and operating on constants or attributes of tuples. select loan_number, branch_name, amount 100 from loan would return a relation that is the same as the loan relation, except that the value of the attribute amount is multiplied by 100.
I The query:
3.<number>
I To find all loan number for loans made at the Perryridge branch with
select loan_number from loan where branch_name = 'Perryridge' and amount > 1200
I Comparison results can be combined using the logical connectives and,
3.<number>
$90,000 and $100,000 (that is, $90,000 and $100,000) select loan_number from loan where amount between 90000 and 100000
3.<number>
select from borrower, loan I 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'
3.<number>
old-name as new-name
I Find the name, loan number and loan amount of all customers; rename the
select customer_name, borrower.loan_number as loan_id, amount from borrower, loan where borrower.loan_number = loan.loan_number
3.<number>
Tuple Variables
I Tuple variables are defined in the from clause via the use of the as
clause.
I Find the customer names and their loan numbers for all customers
select customer_name, T.loan_number, S.amount from borrower as T, loan as S where T.loan_number = S.loan_number
I
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'
3.<number>
String Operations
I SQL includes a string-matching operator for comparisons on character
strings. The operator like uses patterns that are described using two special characters:
G G
percent (%). The % character matches any substring. underscore (_). The _ character matches any character.
I Find the names of all customers whose street includes the substring
Main.
concatenation (using ||) converting from upper to lower case (and vice versa) finding string length, extracting substrings, etc.
3.<number> Silberschatz, Korth and Sudarshan
Perryridge branch
select distinct customer_name from borrower, loan where borrower loan_number = loan.loan_number and branch_name = 'Perryridge' order by customer_name
I We may specify desc for descending order or asc for ascending
3.<number>
Duplicates
I In relations with duplicates, SQL can define how many copies of tuples
(r1): If there are c1 copies of tuple t1 in r1, and t1 satisfies selections ,, then there are c1 copies of t1 in (r1).
(t1) in A (r1) where A (t1) denotes the projection of the single tuple t1. A
3. r1 x r2 : If there are c1 copies of tuple t1 in r1 and c2 copies of tuple t2 in r2, there are c1 x c2 copies of the tuple t1. t2 in r1 x r2
3.<number>
Duplicates (Cont.)
I Example: Suppose multiset relations r1 (A, B) and r2 (C) are as
follows:
r1 = {(1, a) (2,a)}
3.<number>
Set Operations
I The set operations union, intersect, and except operate on relations
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:
G G G
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
3.<number>
Set Operations
I Find all customers who have a loan, an account, or both:
3.<number>
Aggregate Functions
I These functions operate on the multiset of values of a column of
avg: average value min: minimum value max: maximum value sum: sum of values count: number of values
3.<number>
3.<number>
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
3.<number>
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
3.<number>
Null Values
I It is possible for tuples to have a null value, denoted by null, for some
of their attributes
I null signifies an unknown value or that a value does not exist. I The predicate is null can be used to check for null values.
G
Example: Find all loan number which appear in the loan relation with null values for amount. select loan_number from loan where amount is null
3.<number>
or
null = null
OR: (unknown or true) = true, (unknown or false) = unknown (unknown or unknown) = unknown AND: (true and unknown) = unknown, (false and unknown) = false, (unknown and unknown) = unknown NOT: (not unknown) = unknown P is unknown evaluates to true if predicate P evaluates to unknown
G G
unknown
3.<number>
Above statement ignores null amounts Result is null if there is no non-null amount
3.<number>
Nested Subqueries
I SQL provides a mechanism for the nesting of subqueries. I A subquery is a select-from-where expression that is nested within
another query.
3.<number>
Example Query
I Find all customers who have both an account and a loan at the bank.
select distinct customer_name from borrower where customer_name in (select customer_name from depositor )
I Find all customers who have a loan at the bank but do not have
select distinct customer_name from borrower where customer_name not in (select customer_name from depositor )
3.<number>
Example Query
I Find all customers who have both an account and a loan at the
Perryridge branch
select distinct customer_name from borrower, loan where borrower.loan_number = loan.loan_number and branch_name = 'Perryridge' and (branch_name, customer_name ) in (select branch_name, customer_name from depositor, account where depositor.account_number = account.account_number )
I Note: Above query can be written in a much simpler manner. The
3.<number>
Set Comparison
I Find 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'
I Same query using > some clause
select branch_name from branch where assets > some (select assets from branch where branch_city = 'Brooklyn')
3.<number>
(5 < some
0 5 6 0 5 0 5 0 5
) = true
Example Query
I Find the names of all branches that have greater assets than all
select branch_name from branch where assets > all (select assets from branch where branch_city = 'Brooklyn')
3.<number>
(5 < all
0 5 6 6 10 4 5 4 6
) = false
3.<number>
nonempty.
3.<number>
Example Query
I Find all customers who have an account at all branches located in
Brooklyn.
select distinct S.customer_name from depositor as S where not exists ( (select branch_name from branch where branch_city = 'Brooklyn') except (select R.branch_name from depositor as T, account as R where T.account_number = R.account_number and S.customer_name = T.customer_name ))
I Note that X Y = X Y I Note: Cannot write this query using = all and its variants
3.<number>
I Find all customers who have at most one account at the Perryridge
select T.customer_name from depositor as T where 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')
3.<number>
Example Query
I Find all customers who have at least two accounts at the Perryridge
branch.
select distinct 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')
I Variable from outer level is known as a correlation variable
3.<number>
Derived Relations
I SQL allows a subquery expression to be used in the from clause I Find the average account balance of those branches where the average
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 Note that we do not need to use the having clause, since we compute the temporary (view) relation branch_avg in the from clause, and the attributes of branch_avg can be used directly in the where clause.
3.<number>
With Clause
I The with clause provides a way of defining a temporary view whose
definition is available only to the query in which the with clause occurs.
with max_balance (value) as select max (balance) from account select account_number from account, max_balance where account.balance = max_balance.value
3.<number>
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
3.<number>
Views
I In some cases, it is not desirable for all users to see the entire logical
model (that is, all the actual relations stored in the database.)
and branch name, but has no need to see the loan amount. This person should see a relation described, in SQL, by (select customer_name, borrower.loan_number, branch_name from borrower, loan where borrower.loan_number = loan.loan_number )
certain users.
I Any relation that is not of the conceptual model but is made visible to a
3.<number>
View Definition
I A view is defined using the create view statement which has the
form
create view v as < query expression > where <query expression> is any legal SQL expression. The view name is represented by v.
I Once a view is defined, the view name can be used to refer to the
3.<number>
Example Queries
I 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 )
I Find all customers of the Perryridge branch
3.<number>
v2
3.<number>
View Expansion
I A way to define the meaning of views defined in terms of other views. I Let view v1 be defined by an expression e1 that may itself contain uses
repeat Find any view relation vi in e1 Replace the view relation vi by the expression defining vi until no more view relations are present in e1
I As long as the view definitions are not recursive, this loop will
terminate
3.<number>
delete from account where branch_name in (select branch_name from branch where branch_city = 'Needham')
3.<number>
Example Query
I Delete the record of all accounts with balances below the average at
the bank.
delete from account where balance < (select avg (balance ) from account )
G
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)
3.<number>
insert into account values ('A-9732', 'Perryridge', 1200) or equivalently insert into account (branch_name, balance, account_number) values ('Perryridge', 1200, 'A-9732')
I Add a new tuple to account with balance set to null
3.<number>
savings account. Let the loan number serve as the account number for the new savings account insert into account select loan_number, branch_name, 200 from loan where branch_name = 'Perryridge' insert into depositor select customer_name, loan_number from loan, borrower where branch_name = 'Perryridge' and loan.account_number = borrower.account_number
I The select from where statement is evaluated fully before any of its
results are inserted into the relation (otherwise queries like insert into table1 select * from table1 would cause problems)
3.<number>
Write two update statements: update account set balance = balance 1.06 where balance > 10000 update account set balance = balance 1.05 where balance 10000
G G
The order is important Can be done better using the case statement (next slide)
3.<number>
update account set balance = case when balance <= 10000 then balance *1.05 else balance * 1.06 end
3.<number>
Update of a View
I Create a view of all loan data in the loan relation, hiding the amount
attribute
insert into branch_loan values ('L-37, 'Perryridge) This insertion must be represented by the insertion of the tuple ('L-37', 'Perryridge', null ) into the loan relation
3.<number>
create view v as select loan_number, branch_name, amount from loan where branch_name = Perryridge insert into v values ( 'L-99','Downtown', '23')
3.<number>
Joined Relations**
I Join operations take two relations and return as a result another
relation.
I Join condition defines which tuples in the two relations match, and
I 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.
3.<number>
I Relation borrower
I Note: borrower information missing for L-260 and loan information missing for L-155
3.<number>
loan.loan_number = borrower.loan_number
3.<number>
3.<number>
I 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
3.<number>
End of Chapter 3
3.<number>
3.<number>
3.<number>