Lecture5 DBS
Lecture5 DBS
Lecture 5
Dr. Mohammad Assaad 1
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.
SELECT branchNo,
COUNT(staffNo) AS count,
SUM(salary) AS sum
FROM Staff
GROUP BY branchNo
ORDER BY branchNo;
SELECT branchNo,
COUNT(staffNo) AS count,
SUM(salary) AS sum
FROM Staff
GROUP BY branchNo
HAVING COUNT(staffNo) > 1
ORDER BY branchNo;
Staff Table
Staff Table
SELECT column
FROM table1
WHERE column OPERATOR ANY (
SELECT column
FROM table2
);
Dr. Mohammad Assaad 28
SQL ANY and ALL
Here,
SELECT *
FROM Teachers
WHERE age = ANY (
SELECT age
FROM Students
);
Dr. Mohammad Assaad 30
Example 1: SQL ANY Operator
Here, the subquery below returns all the ages from the
Student’s table.
SELECT age
FROM Students
SQL ALL compares a value of the first table with all values
of the second table and returns the row if there is a match
with all values.
SELECT column
FROM table1
WHERE column OPERATOR ALL (
SELECT column
FROM table2
);
Here,
SELECT *
FROM Teachers
WHERE age > ALL (
SELECT age
FROM Students
);
SELECT age
FROM Students
◼ select all the rows from the Customers table with the minimum
age
SELECT *
FROM Customers
WHERE age = (
SELECT MIN(age)
FROM Customers
);
2.executes the outer query; and selects the rows where the
age is equal to the result of the subquery.
Dr. Mohammad Assaad 39
Dr. Mohammad Assaad 40
SQL Subquery With IN Operator
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name comparison_operator ALL
(SELECT column_name
FROM table_name
WHERE condition(s));
Products Table
Dr. Mohammad Assaad 45
Consider the following Products Table and
OrderDetails Table,
OrderDetails
Dr. Mohammad Assaad 46
Queries
SELECT ProductName
FROM Products
WHERE ProductID = ALL (SELECT ProductId
FROM OrderDetails
WHERE Quantity = 6 OR Quantity = 2);
SELECT OrderID
FROM OrderDetails
GROUP BY OrderID
HAVING max(Quantity) > ALL (SELECT avg(Quantity)
FROM OrderDetails
GROUP BY OrderID);
SELECT column_name(s)
FROM table_name
WHERE column_name comparison_operator ANY
(SELECT column_name
FROM table_name
WHERE condition(s));
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID
FROM OrderDetails
WHERE Quantity = 9);