❖ Week 03 Wednesday |
ass1.dump❖ Video Material |
Topic Videos
❖ Exercise: Queries on Simple Beer DB |
Answer these queries on the Beer database:
❖ Problem Solving in SQL |
Developing SQL queries ...
FROMJOINWHEREGROUP BYSELECTViews provide a useful tool for abstraction
❖ Views |
Views are like "virtual tables"
CREATE [OR REPLACE] VIEW ViewName ( AttributeNames ) AS SELECT ResultValues (one per attribute) FROM ... ;
Things to note:
AttributeNamesselect❖ Views (cont) |
Views are very useful in simplifying complex queries
Views look like tables
create or replace viewdrop viewcreate view❖ Views (cont) |
Example view definition:
create table R (x integer, y text, z char(3)); create view RR(a, b) as select x,y from R;
The view RR(integer,text)
You cannot redefine it as e.g.
create view RR(a, b) as select y,z from R;
This has type (text,char(3))
To change the number/types of view attributes:
drop view RR; create view RR(a, b) as select y,z from R;
❖ Views (cont) |
Two ways of defining a view
create or replace view V
as
select x as a1, y as a2, z as a3
from R
where ... ;
-- alternatively
create or replace view V(a1, a2, a3)
as
select x, y, z
from R
where ...;
❖ Exercise: Defining Views on simple Beer DB |
Define the following:
bb(brewery,nbeers)avgprice(bar,price)liked(drinker,beers)❖ Exercise: More queries on Simple Beer DB |
Define views to answer each of the following:
❖ Problem Solving Patterns for SQL |
Example: what is the most expensive beer?
create view maxPrice as select max(price) from Sells; create view highestPriceBeer as select s.beer from Sells s where s.price = (select * from maxPrice);
❖ Problem Solving Patterns for SQL (cont) |
Don't need the view; can calculate "inline"
create view highestPriceBeer as select s.beer from Sells s where s.price = (select max(price) from Sells);
But you always need a query to extract the single value
An example of a common pattern:
❖ Problem Solving Patterns for SQL (cont) |
Note: there may be more than one equally biggest/smallest
The following is not a general solution
create view highestPriceBeer as select s.beer from Sells s order by s.price desc limit 1
Avoid limit
❖ Problem Solving Patterns for SQL (cont) |
Example: what is cheapest beer at each bar?
for each Bar {
find cheapest price at the bar
fine name of beer with this price
}
Needs correlated subquery
select s.bar, s.beer, s.price::numeric(4,2)
from Sells s
where s.price = (select min(s1.price)
from Sells s1
where s1.bar = s.bar);
❖ Problem Solving Patterns for SQL (cont) |
Answering queries like: Which X's are RelatedTo all Y's
AllYs = select Y from Ys
for each X {
YsRelatedToX = select Y from R where ...X...
if YsRelatedToX == AllYs
X is added to the results
}
In SQL, you can't compare sets directly, so
not exists (
(select Y from Ys) -- all Y tuples
except
(select Y from R where ...X...)
)
❖ Problem Solving Patterns for SQL (cont) |
Example: Which beers are sold at all bars?
select b.name
from Beers b
where not exists (
(select name from Bars)
except
(select bar from Sells where beer = b.name)
)
;
❖ Problem Solving Patterns for SQL (cont) |
Some queries require all tuples from RR join S
RS
select d.addr, count(b.id) as nbars
from Drinkers d
left outer join Bars b on d.addr=b.addr
group by d.addr
;
❖ Exercise: SQL Set and Join Operations |
Consider two tables:
R(a char(1), b integer) S(a char(1), c integer) R a | b S a | c -----+----- -----+----- a | 1 a | 2 b | 2 b | 2 c | 3 d | 2 d | 4 e | 2
What is the result of:
R union SR intersect SR except SR join SR natural join SR left outer join S❖ What's wrong with SQL? |
Consider the problem of withdrawal from a bank account:
If a bank customer attempts to withdraw more funds than they have in their account, then indicate "Insufficient Funds", otherwise update the account
An attempt to implement this in SQL:
select 'Insufficient Funds' from Accounts where acctNo = AcctNum and balance < Amount; update Accounts set balance = balance - Amount where acctNo = AcctNum and balance >= Amount; select 'New balance: '||balance from Accounts where acctNo = AcctNum;
❖ What's wrong with SQL? (cont) |
Two possible evaluation scenarios:
UPDATEUPDATEUPDATE(balance < )❖ Database Programming |
Database programming requires a combination of
❖ Database Programming (cont) |
Combining SQL and procedural code solves the "withdrawal" problem:
create function
withdraw(acctNum text, amount integer) returns text
declare bal integer;
begin
set bal = (select balance
from Accounts
where acctNo = acctNum);
if (bal < amount) then
return 'Insufficient Funds';
else
update Accounts
set balance = balance - amount
where acctNo = acctNum;
set bal = (select balance
from Accounts
where acctNo = acctNum);
return 'New Balance: ' || bal;
end if
end;
(This example is actually a stored procedure, using SQL/PSM syntax)
Produced: 1 Oct 2023