COMP3311 Week 3 Wednesday Lecture

COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [0/23]
❖ Week 03 Wednesday

Things to Note ...

Things to do ...

In today's lecture ...

COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [1/23]
❖ Video Material

Topic Videos

Lectures
COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [2/23]
❖ Example Database: Beers/Bars/Drinkers

Consider the following ER model:

[Diagram:Pics/exercises/beer1.png]

COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [3/23]
❖ Exercise: Queries on Simple Beer DB

Answer these queries on the Beer database:

  1. What beers are made by Toohey's?
  2. Show beers with headings "Beer", "Brewer".
  3. How many different beers are there?
  4. How many different brewers are there?
  5. Find pairs of beers by the same manufacturer.
  6. (a) Which beers does John like?
    (b) Find the brewers whose beers John likes.
  7. (a) How many beers does each brewer make?
    (b) Which brewer makes the most beers?
    (c) Which beers are the only one made by their brewer?
COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [4/23]
❖ Problem Solving in SQL

Developing SQL queries ...

Learn some query patterns and know when to apply them

Views provide a useful tool for abstraction

COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [5/23]
❖ Views


Views are like "virtual tables"

CREATE [OR REPLACE] VIEW ViewName ( AttributeNames )
AS
SELECT ResultValues (one per attribute) FROM ... ;

Things to note:

COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [6/23]
❖ Views (cont)

Views are very useful in simplifying complex queries

Views look like tables

If using  create or replace view  you cannot Need to  drop view , then  create view
COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [7/23]
❖ 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 has type (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)), incompatible with the original type.

To change the number/types of view attributes:

drop view RR;
create view RR(a, b) as select y,z from R;

COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [8/23]
❖ 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  ...;

COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [9/23]
❖ Exercise: Defining Views on simple Beer DB



Define the following:

COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [10/23]
❖ Exercise: More queries on Simple Beer DB

Define views to answer each of the following:

  1. Comma-separated list of beers by each brewer
  2. Find the beers sold at bars where John drinks.
  3. Bars where either Gernot or John drink.
  4. Bars where both Gernot and John drink.
  5. Bars where John drinks but Gernot doesn't.
  6. Find bars that serve New at the same price
    as the Coogee Bay Hotel charges for VB.
  7. Find the average price of common beers
    (i.e. served in more than two hotels).
  8. Which bar sells 'New' cheapest?
COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [11/23]
❖ Problem Solving Patterns for SQL

Example: what is the most expensive beer?

As SQL:

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);

COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [12/23]
❖ 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:

E.g.   X = name,   Y = beer,   Z = price
COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [13/23]
❖ 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 unless doing e.g. pagination.

COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [14/23]
❖ 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);

COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [15/23]
❖ 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...)
)

COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [16/23]
❖ 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)
       )
;

COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [17/23]
❖ Problem Solving Patterns for SQL (cont)


Some queries require all tuples from R to appear in   R join S

Example: How many bars in are there in suburbs where drinkers live?

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
;

COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [18/23]
❖ 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:

COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [19/23]
❖ 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;

COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [20/23]
❖ What's wrong with SQL? (cont)

Two possible evaluation scenarios:

Some problems: To accurately express the "business logic", we need facilities like conditional execution and parameter passing.
COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [21/23]
❖ Database Programming

Database programming requires a combination of

This combination is realised in a number of ways:
COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [22/23]
❖ 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)

COMP3311 23T3 ♢ Week 3 Wednesday Lecture ♢ [23/23]


Produced: 1 Oct 2023