L08 SQL
L08 SQL
Dr Renata Borovica-Gajic
Lecture 08
SQL
2.
3.
• We looked at Customer
– A customer can have a number of Accounts
– The tables get linked through a foreign key
2)
No column specification means
ALL columns need to be entered
Customer
CustID CustomerFirst CustMiddle CustLastName BusinessName CustType
Name Name
1 Peter NULL Smith NULL Personal
2 James NULL Jones JJ Enterprises Company
3 NULL Smythe Company
All columns
SQL
RESULT
SQL
Result
In Relational Algebra:
CustLastName(Customer)
In SQL:
SELECT CustLastName
FROM Customer;
NOTE: MySQL doesn’t discard duplicates.
To remove them use DISTINCT in front of
the projection list.
In SQL: In SQL:
WHERE cond1 AND cond2 SELECT CustLastName
OR cond3 FROM Customer
WHERE CustLastName = “Smith”;
SQL
Result
Examples: SQL:
WHERE CustomerName Finds any values that start with "a"
LIKE 'a%'
WHERE CustomerName Finds any values that end with "a"
LIKE '%a' Result
WHERE CustomerName Finds any values that have "or" in
LIKE '%or%' any position
WHERE CustomerName Finds any values that have "r" in the
LIKE '_r%' second position
WHERE CustomerName Finds any values that start with "a"
LIKE 'a_%_%' and are at least 3 characters in
length
WHERE ContactName Finds any values that start with "a"
LIKE 'a%o' and end with "o"
• All of these except for COUNT(*) ignore null values and return
null if all values are null. COUNT(*) counts the number of
records.
INFO20003 Database Systems © University
- - of Melbourne 20
Aggregate Examples: Count/AVG
Examples:
SELECT COUNT(CustomerID) = How many customers do we have
FROM Customer; (cardinality)
SELECT AVG(OutstandingBalance)
= What is the average balance of
FROM Account
Accounts of Customer 1
WHERE CustomerID= 1;
• Example:
What is the average balance PER CUSTOMER
SELECT AVG(OutstandingBalance)
FROM Account
GROUP BY CustomerID;
Returns one record per each customer
• The HAVING clause was added to SQL because the WHERE keyword
cannot be used with aggregate functions
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
• Example:
List the number of customers of each country, but ONLY include
countries with more than 5 customers
SELECT COUNT(CustomerID), CountryName
FROM Customers
GROUP BY CountryName
HAVING COUNT(CustomerID) > 5;Condition over the aggregate
SQL
RESULT
• Inner/Equi join:
– Joins the tables over keys
CONDITION
• Natural Join:
– Joins the tables over keys. The condition does not have to be specified
(natural join does it automatically), but key attributes have to have the
same name.
• Outer join:
– Joins the tables over keys
– Can be left or right (see difference below)
– Includes records that don’t match the join from the other table
T1.ID T2.ID
T1.ID T2.ID
T1.ID T2.ID
✅ ✅
T1.ID T2.ID
✅ ✅
T1.ID T2.ID
✅ ✅ ✅
• SQL Summary
‒ Overview of concepts, more examples