3. SQL
3
Fall 2001 Database Systems 5
SQL - Nested Statements
• A nested sub-expression may refer to the tuples from the outer
relation
SELECT Buy.Name
FROM Buyers Buy
WHERE Buy.BuyId IN (
SELECT B.BuyID
FROM Bids B
WHERE B.Amount 20 AND
B.BuyID NOT IN (
SELECT B2.BuyID
FROM Bids B2
WHERE B2.Amount = 20
AND B2.Iid = B.Iid))
Names of buyers with a bid
greater than 20 on an item
for which the buyer has no
other bids less than 20.
Fall 2001 Database Systems 6
Nested Structures - Exists
SELECT
FROM
WHERE (NOT) EXISTS
(SELECT *
FROM R1, ..., Rm
WHERE P)
• Semantics: For each tuple of the outer query, execute
the inner query; if there is at least one (no) tuple in the
result of the inner query, then retrieve that tuple of the
outer query.
• This accounts for the “there exists” type of queries
4. SQL
4
Fall 2001 Database Systems 7
SQL Nested Statements
• Two more nested conditions:
– EXISTS ( SELECT … FROM … WHERE … ) is true if the
SFW clause returns a non-empty relation
– NOT EXISTS ( SELECT … FROM … WHERE … ) is true if
the SFW clause returns an empty relation
• Find the name of all buyers who have no bids with an amount less
than 50
SELECT Buy.Name
FROM Buyers Buy
WHERE NOT EXISTS (SELECT B.BuyId
FROM Bids B
WHERE B.Amount 50 AND
B.BuyID=Buy.BuyId)
Fall 2001 Database Systems 8
SQL - EXISTS
• Find the names of buyers who placed a bid on
all items with one or more bids
SELECT Buy.Name
FROM Buyers Buy
WHERE EXISTS (
SELECT B.Iid
FROM Bids B
WHERE Buy.BuyId = B.BuyId)
Is this correct?
Names of buyers who
have bid on an item
Find buyers such that there does not exist an
item with bids on which these buyers did not bid
5. SQL
5
Fall 2001 Database Systems 9
SQL - EXISTS
• Find the names of buyers who placed a bid on all items
with one or more bids
SELECT Buy.Name
FROM Buyers Buy
WHERE NOT EXISTS (
SELECT B.Iid
FROM Bids B
WHERE NOT EXISTS (
SELECT *
FROM Bids B2
WHERE B.Iid = B2.Iid AND
B2.Buyid = Buy.BuyId) )
bids for this item
by this buyer
items with bids, but
not by this buyer
either there are no bids
or this buyer has a bid
on everything
Fall 2001 Database Systems 10
Things to Think About
• Don’t use nested queries if they are not
needed.
– they make the query unnecessarily
complicated
– they make optimization harder
• If a query requires only “IN” and “EXISTS”,
then it probably can be done without nesting.
6. SQL
6
Fall 2001 Database Systems 11
Aggregate functions
• Count, Max, Min, Sum, and Avg are aggregate functions
that apply to the values of a set of tuples
• Find the total number of bids in the bids table
SELECT Count(*)
FROM Bids
• Find the average bid for the “Dipping Bird”.
SELECT Avg(B.Amount) AS AvgAmt
FROM Bids B, Items I
WHERE B.Iid = I.Iid AND I.Name = ‘Dipping Bird’
Fall 2001 Database Systems 12
Aggregate Functions
• Find the buyer(s) who placed the maximum bid on the “Dipping
Bird”
SELECT DISTINCT B2.Buyid
FROM Bids B2, Items I2
WHERE B2.Iid=I2.Iid AND
I2.Name = ‘Dipping Bird’ AND
B2.Amount = (SELECT Max(B.Amount)
FROM Bids B, Items I
WHEREB.Iid = I.Iid AND
I.Name = ‘Dipping Bird’)
7. SQL
7
Fall 2001 Database Systems 13
Grouping
SELECT a
FROM b
WHERE c
GROUP BY d
Create the Cartesian product of the relations in b
Find all tuples from the Cartesian product that satisfy the condition in c
(including any subexpressions)
For all distinct values of the columns listed in d, create a group that
contains the set of tuples with that value for “d”
Create the columns in a, which should start with columns in d and end
with aggregates that will apply to each group separately.
Fall 2001 Database Systems 14
Group by
• Find the average bid amount for each item, list
the item name, the average bid and the number
of bids
SELECT I.name,
avg(B.Amount) AS AvgBid,
count(*) AS Cnt
FROM Items I, Bids B
WHERE I.Iid = B.Iid
GROUP BY I.name
10. SQL
10
Fall 2001 Database Systems 19
• Find owners who have at least two items with
average bids greater than $20 for each item. List the
owner identifiers and the names of the items.
SELECT I2.Oid, I2.Name
FROM Items I2
WHERE I2.Oid IN (
SELECT I.Oid
FROM Items I
WHERE I.Iid IN (
SELECT B.Iid
FROM Bids B
GROUP BY B.Iid
HAVING Avg(Amount) 20)
GROUP BY I.Oid HAVING Count(*) = 2)
AND I2.Iid IN (
SELECT B.Iid
FROM Bids B
GROUP BY B.Iid
HAVING Avg(Amount) 20)
Fall 2001 Database Systems 20
ORDER BY
• Follows group by and orders the results in ascending or
descending order
• Example: Find buyer and item pairs in which the buyer has
more than one bid for the item, order the result in descending
order of buyer ids
SELECT B.buyid, B.iid
FROM Bids B
GROUP BY B.buyid, B.iid HAVING count(B.bid) 1
ORDER BY B.buyid DESC
11. SQL
11
Fall 2001 Database Systems 21
SELECT complete
• First the Cartesian product of all tables in the from clause is formed
• From this, rows not satisfying the where condition are eliminated
• The remaining rows are grouped in accordance with the group by
clause
• Groups not satisfying the having clause then eliminated
• The expressions of the select clause target list are evaluated
• If the key word distinct is present, duplicate rows are now
eliminated
• The union is taken after each Subselect is evaluated
• Finally, the set of all result rows is sorted if an order by clause is
present.
Fall 2001 Database Systems 22
Join types
• It is possible to define a join in the from clause
– INNER JOIN: regular join from relational algebra
where only tuples from the two tables satisfying the
join condition are chosen
– LEFT OUTER JOIN: (regular join) union (tuples from
the table to the left that did not join with any tuples,
padded with null values for the new attributes)
– RIGHT OUTER JOIN: (regular join) union (tuples from
the table to the right that did not join with any tuples,
padded with null values for the new attributes)
– FULL JOIN = LEFT RIGHT OUTER JOIN
14. SQL
14
Fall 2001 Database Systems 27
Example 2
• Find the identifiers and amount of bids placed by
buyer “Roberts”
SELECT B.Bid, B.Amount
FROM Bids B, Buyers Buy
WHERE Buy.Name = ‘Roberts’ AND
Buy.Buyid = B.Buyid
Fall 2001 Database Systems 28
Example 3
• Find the names of buyers who placed a bid on an
item owned by “Brown”
SELECT DISTINCT Buy.Name
FROM Bids B, Buyers Buy, Owners O, Items I
WHERE O.Name = ‘Brown’ AND
O.Oid = I.Oid AND
I.Iid = B.Iid AND
B.Buyid = Buy.Buyid
15. SQL
15
Fall 2001 Database Systems 29
Example 4
• Find the identifier of items with more than one bid
SELECT B.Iid
FROM Bids B
GROUP BY B.Iid HAVING count(B.Bid) 1
or
SELECT DISTINCT B.Iid
FROM Bids B
WHERE EXISTS (
SELECT *
FROM Bids B2
WHERE B2.Iid = B.Iid AND B2.Bid B.Bid)
Fall 2001 Database Systems 30
Example 5
• Find the names of items all buyers placed a bid on
Find the names of items for which there does not exist a buyer
who did not place a bid on this item
SELECT I.name
FROM Items I
WHERE NOT EXISTS (
SELECT *
FROM Buyers Buy
WHERE NOT EXISTS (
SELECT *
FROM Bids B
WHERE Buy.Buyid = B.Buyid AND
B.Iid = I.Iid ))
16. SQL
16
Fall 2001 Database Systems 31
Expressions
• Each predicate in the WHERE clause can evaluate to
– TRUE
– FALSE
– UNKNOWN
• Example:
SELECT B.*
FROM Bids B
WHERE B.amount (SELECT max(B1.amount)
FROM Bids B1, Items I
WHERE B1.iid=I.iid AND
I.location = “Boston”)
What if there are no tuples
in this expression?
Fall 2001 Database Systems 32
Unknown expressions
• Expressions that compare a value against a possibly null
value return the truth value “Unknown” (U).
• Logically Unknown is different than True or False.
– Not U = U
– U and True = U
– U and U = U
– U and False = False
– U or True = True
– U or U = U
– U or False = U
17. SQL
17
Fall 2001 Database Systems 33
Unknown Expressions
• Unknown valued tuples do not contribute to a query result
SELECT B.*
FROM Bids B
WHERE B.amount ALL (SELECT B1.amount
FROM Bids B1, Items I
WHERE B1.iid=I.iid AND
I.location = “Boston”)
This query will not return any tuples if the amount for
some bids in Boston is “null”.
Fall 2001 Database Systems 34
Data Management
• Creating tables, inserting and deleting tuples, and updating
column values can be done by SQL statement.
CREATE TABLE tablename
( colname1 TYPE [NOT NULL],
…,
PRIMARY KEY(colname1,…)
)
INSERT INTO tablename(colname1,colname2,…)
VALUES (…)
18. SQL
18
Fall 2001 Database Systems 35
More Data Management
• Insert can also involve a SELECT condition
INSERT INTO BUYERS(buyid,name, email)
SELECT next(buyid), O.name, O.email
FROM Owners O
WHERE NOT EXISTS (SELECT * FROM Buyers B
WHERE B.name=O.name
AND B.email=O.email)
Fall 2001 Database Systems 36
Delete
• The Delete statement involves a “WHERE” condition that
specifies the range of tuples that should be deleted from the
relation.
DELETE FROM Bids
WHERE Bids.Iid IN (SELECT I.iid FROM Items I
WHERE I.oid = ‘O1’)
19. SQL
19
Fall 2001 Database Systems 37
Update
• The Update statement includes a range condition
(WHERE) and a set condition for the new values.
• For each tuple t that satisfies the where condition,
run the expression in the set statement.
UPDATE items
SET avgbid = (SELECT avg(B.amount)
FROM Bids B
WHERE B.iid = items.iid)
WHERE items.location = ‘Boston’