0% found this document useful (0 votes)
15 views

Lecture5 DBS

The document discusses SQL grouping, aggregation, and subqueries. It explains how to use GROUP BY to get subtotals and aggregate functions. It provides examples of grouping, having, and subqueries using operators like equality, IN, ANY, and ALL.

Uploaded by

ar44122010
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Lecture5 DBS

The document discusses SQL grouping, aggregation, and subqueries. It explains how to use GROUP BY to get subtotals and aggregate functions. It provides examples of grouping, having, and subqueries using operators like equality, IN, ANY, and ALL.

Uploaded by

ar44122010
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Database System- SQL

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.

Dr. Mohammad Assaad 2


SELECT Statement - Grouping
⚫ 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.
Dr. Mohammad Assaad 3
Example 4.1 Use of GROUP BY
⚫ Find number of staff in each branch and their total
salaries.

SELECT branchNo,
COUNT(staffNo) AS count,
SUM(salary) AS sum
FROM Staff
GROUP BY branchNo
ORDER BY branchNo;

Dr. Mohammad Assaad 4


Example 4.1 Use of GROUP BY

Dr. Mohammad Assaad 5


Example 4.1 Use of GROUP BY

Dr. Mohammad Assaad 6


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.

Dr. Mohammad Assaad 7


Example 4.2 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 count,
SUM(salary) AS sum
FROM Staff
GROUP BY branchNo
HAVING COUNT(staffNo) > 1
ORDER BY branchNo;

Dr. Mohammad Assaad


8
Example 4.2 Use of HAVING

Staff Table

Dr. Mohammad Assaad 9


Example 4.2 Use of HAVING

Dr. Mohammad Assaad 10


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.
Dr. Mohammad Assaad 11
Example 4.3 Subquery with Equality

List staff who work in branch at ‘163 Main St’.

SELECT staffNo, fName, lName, position


FROM Staff
WHERE branchNo =
(SELECT branchNo
FROM Branch
WHERE street = ‘163 Main St’);

Dr. Mohammad Assaad 12


Example 4.3 Subquery with Equality

Staff Table

branch Table Dr. Mohammad Assaad 13


Example 4.4 Subquery with Equality

⚫ Inner SELECT finds branch number for branch at ‘163


Main St’ (‘B003’).

⚫ Outer SELECT then retrieves details of all staff who


work at this branch.

⚫ Outer SELECT then becomes:

SELECT staffNo, fName, lName, position


FROM Staff
WHERE branchNo = ‘B003’;
Dr. Mohammad Assaad 14
Example 4.5 Subquery with Equality

Dr. Mohammad Assaad 15


Example 4.6 Subquery with Aggregate

List all staff whose salary is greater than the average


salary, and show by how much.

SELECT staffNo, fName, lName, position,


salary – (SELECT AVG(salary) FROM Staff) As SalDiff
FROM Staff
WHERE salary >
(SELECT AVG(salary)
FROM Staff);

Dr. Mohammad Assaad 16


Example 4.7 Subquery with
Aggregate
⚫ Cannot write ‘WHERE salary > AVG(salary)’

⚫ Instead, use subquery to find average salary (17000),


and then use outer SELECT to find those staff with
salary greater than this:

SELECT staffNo, fName, lName, position,


salary – 17000 As salDiff
FROM Staff
WHERE salary > 17000;

Dr. Mohammad Assaad 17


Example 4.7 Subquery with
Aggregate

Dr. Mohammad Assaad 18


Subquery Rules

⚫ ORDER BY clause may not be used in a subquery


(although it may be used in outermost SELECT).

⚫ Subquery SELECT list must consist of a single column


name or expression, except for subqueries that use
EXISTS.

⚫ By default, column names refer to table name in FROM


clause of subquery. Can refer to a table in FROM using
an alias.

Dr. Mohammad Assaad 19


Subquery Rules

⚫ When subquery is an operand in a comparison,


subquery must appear on right-hand side.

⚫ A subquery may not be used as an operand in an


expression.

Dr. Mohammad Assaad 20


Example 4.8 Nested subquery:
use of IN
List properties handled by staff at ‘163 Main St’.
SELECT propertyNo, street, city, postcode, type, rooms, rent
FROM PropertyForRent
WHERE staffNo IN
(SELECT staffNo
FROM Staff
WHERE branchNo =
(SELECT branchNo
FROM Branch
WHERE street = ‘163 Main St’));

Dr. Mohammad Assaad 21


Example 4.9 Nested subquery:
use of IN

Dr. Mohammad Assaad 22


ANY and ALL
⚫ ANY and ALL may be used with subqueries that produce a
single column of numbers.

⚫ With ALL, condition will only be true if it is satisfied by all


values produced by subquery.

⚫ With ANY, condition will be true if it is satisfied by any


values produced by subquery.

⚫ If subquery is empty, ALL returns true, ANY returns false.

⚫ SOME may be used in place of ANY.

Dr. Mohammad Assaad 23


Example 4.10 Use of ANY/SOME

Find staff whose salary is larger than salary of at least one


member of staff at branch B003.

SELECT staffNo, fName, lName, position, salary


FROM Staff
WHERE salary > SOME
(SELECT salary
FROM Staff
WHERE branchNo = ‘B003’);

Dr. Mohammad Assaad 24


Example 4.11 Use of ANY/SOME

⚫ Inner query produces set {12000, 18000, 24000} and outer


query selects those staff whose salaries are greater than
any of the values in this set.

Dr. Mohammad Assaad 25


Example 4.12 Use of ALL
Find staff whose salary is larger than salary of every member
of staff at branch B003.

SELECT staffNo, fName, lName, position, salary


FROM Staff
WHERE salary > ALL
(SELECT salary
FROM Staff
WHERE branchNo = ‘B003’);

Dr. Mohammad Assaad 26


Example 4.12 Use of ALL

Dr. Mohammad Assaad 27


SQL ANY and ALL
⚫ SQL ANY compares a value of the first table
with all values of the second table and
returns the row if there is a match with any
value.
⚫ It has the following syntax:

SELECT column
FROM table1
WHERE column OPERATOR ANY (
SELECT column
FROM table2
);
Dr. Mohammad Assaad 28
SQL ANY and ALL

Here,

•column is the name of the column(s) to filter


•table1 and table2 are the two tables to compare
•OPERATOR is any SQL operator to connect the two
queries
•ANY compares table1 and table2 to see if there are
any matches

Dr. Mohammad Assaad 29


Example 1: SQL ANY Operator

Suppose we want to find teachers whose age is similar to


any of the student's age. Then, we can use the following
query:

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

Dr. Mohammad Assaad 31


Dr. Mohammad Assaad 32
SQL ALL Operator

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.

It has the following syntax:

SELECT column
FROM table1
WHERE column OPERATOR ALL (
SELECT column
FROM table2
);

Dr. Mohammad Assaad 33


SQL ALL Operator

Here,

⚫ column is the name of the column(s) to filter


⚫ table1 and table2 are the two tables to compare
⚫ OPERATOR is any SQL operator to connect the two
queries
⚫ ALL compares table1 and table2 to see if all the values
match

Dr. Mohammad Assaad 34


Example 2: SQL ALL Operator

For example, if we want to find teachers whose age is


greater than all students, we can use:

SELECT *
FROM Teachers
WHERE age > ALL (
SELECT age
FROM Students
);

Dr. Mohammad Assaad 35


Example 2: SQL ALL Operator

⚫ Here, the subquery below returns all the ages from


the Student’s table.

SELECT age
FROM Students

Dr. Mohammad Assaad 36


Dr. Mohammad Assaad 37
Example: SQL Subquery

◼ select all the rows from the Customers table with the minimum
age

SELECT *
FROM Customers
WHERE age = (
SELECT MIN(age)
FROM Customers
);

Dr. Mohammad Assaad 38


Example: SQL Subquery

In a subquery, the outer query's result depends on the result


set of the inner subquery. That's why subqueries are also
called nested queries.

Here, the SQL command

1.executes the subquery first; and selects the


minimum age from the Customers table.

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

Suppose we want the details of customers who have placed


an order. Here's how we can do that using a subquery:

◼ select the customers who have made orders

SELECT customer_id, first_name


FROM Customers
WHERE customer_id IN (
SELECT customer_id
FROM Orders
);
Dr. Mohammad Assaad 41
SQL Subquery With IN Operator

Here, the SQL command

1. selects customer_id from the Orders table


2. select those rows from the Customers table where
customer_id is in the result set of the subquery

Dr. Mohammad Assaad 42


Dr. Mohammad Assaad 43
SQL | ALL and ANY

ALL with WHERE or HAVING Statement:

Syntax:

SELECT column_name(s)
FROM table_name
WHERE column_name comparison_operator ALL
(SELECT column_name
FROM table_name
WHERE condition(s));

Dr. Mohammad Assaad 44


Consider the following Products Table and
OrderDetails Table,

Products Table
Dr. Mohammad Assaad 45
Consider the following Products Table and
OrderDetails Table,

OrderDetails
Dr. Mohammad Assaad 46
Queries

•Find the name of the all the product.

SELECT ALL ProductName


FROM Products
WHERE TRUE;

Dr. Mohammad Assaad 47


The Output

Dr. Mohammad Assaad 48


Queries

•Find the name of the product if all the records in the


OrderDetails has Quantity either equal to 6 or 2.

SELECT ProductName
FROM Products
WHERE ProductID = ALL (SELECT ProductId
FROM OrderDetails
WHERE Quantity = 6 OR Quantity = 2);

Dr. Mohammad Assaad 49


The Output

Dr. Mohammad Assaad 50


Queries

•Find the OrderID whose maximum Quantity among all product


of that OrderID is greater than average quantity of all OrderID.

SELECT OrderID
FROM OrderDetails
GROUP BY OrderID
HAVING max(Quantity) > ALL (SELECT avg(Quantity)
FROM OrderDetails
GROUP BY OrderID);

Dr. Mohammad Assaad 51


The Output

Dr. Mohammad Assaad 52


SQL : ANY

•ANY must be preceded by comparison operators. Syntax:

SELECT column_name(s)
FROM table_name
WHERE column_name comparison_operator ANY
(SELECT column_name
FROM table_name
WHERE condition(s));

Dr. Mohammad Assaad 53


SQL : ANY Queries

Find the Distinct CategoryID of the products that have any


record in OrderDetails Table.

SELECT DISTINCT CategoryID


FROM Products
WHERE ProductID = ANY (SELECT ProductID
FROM OrderDetails);

Dr. Mohammad Assaad 54


The output

Dr. Mohammad Assaad 55


SQL : ANY Queries

• Find any records in the OrderDetails table that


Quantity = 9.

SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID
FROM OrderDetails
WHERE Quantity = 9);

Dr. Mohammad Assaad 56


The output

Dr. Mohammad Assaad 57

You might also like