QL SQL1 4
QL SQL1 4
QL SQL1 4
2 4
Simple Queries Queries With Tuple Variables
branch (bname, address, city, assets) loan(accno, cname, bname, amount)
deposit(accno, cname, bname, balance)
Find the names of all branches with assets
greater than $2,500,000. Find customers who have both loans and deposits.
SELECT bname
FROM branch SELECT loan.cname
WHERE assets > 2500000 FROM loan, deposit
WHERE loan.cname = deposit.cname
Find the names of all branches in Edmonton Equivalently using tuple variables:
with assets greater than $2,500,000.
SELECT bname SELECT l.cname
FROM branch FROM loan l, deposit d
WHERE l.cname = d.cname
WHERE assets>2500000 AND city=‘Edmonton’
9 11
10 12
Working with Strings (cont) Ordering the Results
customer(cname, street, city) branch (bname, address, city, assets)
Find the names and assets of all
Find every customer whose address starts branches with assets greater than
with “Computing Science”. $2,500,000 and order the result in
SELECT *
FROM customer ascending order of asset values.
WHERE address LIKE ‘Computing Science%’
SELECT bname, assets
Expression: col-name [NOT] LIKE pattern FROM branch
• Pattern may include wildcard characters ‘%’ WHERE assets > 2500000
matching any string and ‘_’ (underscore) matching ORDER BY assets
any single character.
14 16
Queries With Set Operators Queries Over Multiple Relations
List deposit-holders who have no loans.
branch (bname, address, city, assets)
(SELECT cname
FROM deposits) customer(cname, street, city)
deposit(accno, cname, bname, balance)
MINUS
(SELECT city Find the names and assets of any branch which has
FROM branch) deposit account holders living in Jasper.
17 19
22 24
Nested Structures Using
“EXISTS” Construct Example
“>ALL”, …
branch (bname, address, city, assets)
customer(cname, street, city)
branch (bname, address, city, assets) Find the names of customers who live in a city with
no bank branches.
Find branches that have assets greater than SELECT cname
FROM customer
the assets of all branches in Calgary. WHERE NOT EXISTS (SELECT *
FROM branch
SELECT bname WHERE customer.city=branch.city)
FROM branch
WHERE assets > ALL Find the names of customers who live in a city
(SELECT assets which has a bank branch.
FROM branch
WHERE city = ‘Calgary’) • Change NOT EXISTS to EXISTS.
(can also write it using join)
25 27
26 28
Division Division – 2nd SQL Solution
Find customers who have deposit accounts in all
branches.
Strategy for implementing division in SQL: • Same as “find all customers such that there is no
branch where they do not have deposits in.”
• Find set, A, of all branches in which a particular
customer, c, has a deposit account. SELECT c.cname
FROM customer c
• Find set, B, of all branches. WHERE NOT EXISTS
• Output c if A ⊇ B, or, equivalently, if B–A is (SELECT bname
FROM branch b branches where
empty WHERE NOT EXISTS c has no deposits in
(SELECT *
Deposits of c in FROM deposit
branch b WHERE b.bname=deposit.bname
AND c.cname = deposit.cname))
29 31
34 36