CNG351 Lecture 10 DML Part 1
CNG351 Lecture 10 DML Part 1
“SELECT - JOIN”
Example:
How many properties cost more than £350 per month to rent?
SELECT COUNT(*) AS myCount
FROM PropertyForRent
WHERE rent > 350;
Use of COUNT(DISTINCT)
How many different properties viewed in May ‘04?
SELECT COUNT(DISTINCT propertyNo) AS myCount
FROM Viewing
WHERE viewDate BETWEEN ‘1-May-04’
AND ‘31-May-04’;
Use of COUNT and SUM
Find number of Managers and sum of their salaries.
SELECT COUNT(staffNo) AS myCount,
SUM(salary) AS mySum
FROM Staff
WHERE position = ‘Manager’;
Use of MIN, MAX, AVG
Find minimum, maximum, and average staff salary.
SELECT MIN(salary) AS myMin,
MAX(salary) AS myMax,
AVG(salary) AS myAvg
FROM Staff;
SELECT Statement - Grouping
• Use GROUP BY clause to get sub-totals.
• SELECT and GROUP BY closely integrated: each item in SELECT
list must be single-valued per group, and SELECT clause may only
contain:
– column names
– aggregate functions
– constants
– expression involving combinations of the above.
• All column names in SELECT list must appear in GROUP BY
clause unless name is used only in an aggregate function.
• If WHERE is used with GROUP BY, WHERE is applied first, then
groups are formed from remaining rows satisfying predicate.
• ISO considers two nulls to be equal for purposes of GROUP BY.
Use of GROUP BY
Find number of staff in each branch and their total salaries.
SELECT branchNo,
COUNT(staffNo) AS myCount,
SUM(salary) AS mySum
FROM Staff
GROUP BY branchNo
ORDER BY branchNo;
Restricted Groupings – HAVING clause
• HAVING clause is designed for use with GROUP BY to restrict
groups that appear in final result table.
• Similar to WHERE, but WHERE filters individual rows whereas
HAVING filters groups.
• Column names in HAVING clause must also appear in the GROUP
BY list or be contained within an aggregate function.
Use of HAVING
For each branch with more than 1 member of staff, find number of
staff in each branch and sum of their salaries.
SELECT branchNo,
COUNT(staffNo) AS myCount,
SUM(salary) AS mySum
FROM Staff
GROUP BY branchNo
HAVING COUNT(staffNo) > 1
ORDER BY branchNo;
Subqueries
• Some SQL statements can have a SELECT embedded within
them.
• A subselect can be used in WHERE and HAVING clauses of an
outer SELECT, where it is called a subquery or nested query.
• Subselects may also appear in INSERT, UPDATE, and DELETE
statements.
Subquery with Equality
List staff who work in branch at ‘163 Main St’.