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

Lab4 - DML3 - DML4

The document discusses SQL aggregate functions, group by clauses, and subqueries. It provides examples of using aggregate functions like COUNT and SUM to summarize data, examples of grouping data and using HAVING to filter groups, and examples of different types of subqueries used in WHERE clauses like IN, EXISTS, and NOT EXISTS.

Uploaded by

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

Lab4 - DML3 - DML4

The document discusses SQL aggregate functions, group by clauses, and subqueries. It provides examples of using aggregate functions like COUNT and SUM to summarize data, examples of grouping data and using HAVING to filter groups, and examples of different types of subqueries used in WHERE clauses like IN, EXISTS, and NOT EXISTS.

Uploaded by

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

Cairo University

Faculty of Computers and Artificial Intelligence


Information Systems Department

Database I, Year 2022/ 2023


Lab - 4
DML 3 (Aggregate/group By Functions)
DML 4 (Subqueries)

Part (1) (set operations, Aggregations, group by and having)


Set operations: allow the results of multiple queries to be combined into a single result set.[1] Set
operators include UNION , INTERSECT , and EXCEPT.

1- UNION OPERATOR: combines the results of two SQL queries into a single table of all
matching rows. The two queries must result in the same number of columns and
compatible data types in order to unite. Any duplicate records are automatically removed
unless UNION ALL is used.

2- INTERSECT OPERATOR: takes the results of two queries and returns only rows that
appear in both result sets. The INTERSECT operator removes duplicate rows from the final
result set. The INTERSECT ALL operator does not remove duplicate rows from the final
result set.

3- EXCEPT OPERATOR: takes the distinct rows of one query and returns the rows that do not
appear in a second result set. The EXCEPT ALL operator does not remove duplicates.

Aggregate functions are used to summarize information from multiple tuples into a single-tuple
summary.
Grouping is used to create subgroups of tuples before summarization

Example1: SELECT CustomerID FROM Customers EXCEPT


SELECT CustomerID FROM Orders
Get the customers IDS who didn’t
make any order.
Example 2: SELECT Suppliers.CompanyName

FROM Products, Suppliers, Categories


Get all names of suppliers who supply
products of category named WHERE Suppliers.SupplierID =
‘Beverages’ and products of category Products.SupplierID
named ‘Condiments’
AND Products.CategoryID
=Categories.CategoryID
AND Categories.CategoryName ='Beverages'

INTERSECT

SELECT Suppliers.CompanyName

FROM Products, Suppliers, Categories

WHERE Suppliers.SupplierID
=Products.SupplierID

AND Products.CategoryID
=Categories.CategoryID

AND Categories.CategoryName ='Condiments'

Example 3: SELECT ContactName AS Name,Address,


City,PostalCode
For a mass-mailing purpose, get the
list of all names, addresses, cities and FROM Customers
postal codes known to the database
and remove duplicates from the result UNION
if any (these data are stored in the
customers and employees tables). SELECT FirstName+' '+LastName AS Name,
Address, City,PostalCode

FROM Employees

Example 4: SELECT ProductID, count(od.orderid) as


numOfOrders, Sum(quantity) as
For each product ordered in March totalQuantityOrdered
1998, get the product id, number of FROM [Order Details] od, orders o
orders for that product and the total where od.OrderID = o.OrderID
quantity ordered. Give suitable and year(OrderDate) ='1998'
name(s) for any unnamed displayed and month(OrderDate) = '3'
column(s). Sort by total quantity GROUP BY ProductID
descendingly Order by TotalQuantityOrdered desc

Comments:

1. All the columns in the select with the aggregate


function should be included in the group by clause. In
the example, the GROUP BY will give you one value
(the numer of orders) for each ProductID.
2. In this query, if we have a column next to the aggregate
function in the select caluse, we have to write a
GROUP BY this column. Otherwise, an error will be
given because we are trying to tell the DBMS to show
ProductID “Multipe Values” next to an aggregate
function.
3. If we removed the other column(s) in the select and the
GROUP BY and keep only the aggregate functions.
The SUM/COUNT will get us the sum of quantities
and total number of orders for the whole table at once.

Example 5: SELECT ContactName, Count (ProductID) AS


NumberOfSuppliedProducts
Get the supplier names (Contact FROM Products, Suppliers
names) and the total number of where Products.SupplierID =
supplied products for each supplier, Suppliers.SupplierID
for only those suppliers that supplied GROUP BY ContactName
more than 3 products. Give suitable HAVING Count (ProductID) > 3
name(s) for any unnamed displayed
column(s). Comments:
1. HAVING, this clause could be written only in case you
have a GROUP BY clause. It is a filtering condition that
will be applied on the resultant groups, to filter the groups
which do not satisfy the given condition.
2. Conditions which are applied to the data before
grouping (the raw data not the aggregated groups) , should
be put in the where clause not the HAVING.
Example 6: SELECT CustomerID, COUNT (o.OrderID) AS
NumberOfOrders, MAX (OrderDate) AS
For all customers with at least 15 LastOrderDate, Avg(Unitprice) as
orders after 1996, get the customer id, AveragePrice
total number of orders, the last order FROM Orders o, [order details] od
date and the average unit price for WHERE o.OrderID = od.orderid
products in his/her orders . Give and YEAR (OrderDate) > 1996
suitable name(s) for any unnamed GROUP BY CustomerID
displayed column(s). Display the HAVING COUNT (o.OrderID) > 15
result starting from customers with and Avg(unitPrice)> 25
the highest number of orders. ORDER BY COUNT (o.OrderID) DESC
Part (2) (Nested Queries)

A Subquery is a query within another query. Subqueries can reside in WHERE Clause, FROM
Clause or SELECT Clause.

1. Using Sub-queries in the where clause – IN

1. Display the first name, title of all employees who live in UK and have the
same job (title) as Janet or Steven. Sort the result by the first name of the
employees in a descending order.

SELECT FirstName, Title


FROM Employees
WHERE Country = 'UK'
AND Title IN (SELECT Title
FROM Employees
WHERE FirstName IN ('Janet', 'Steven'))
ORDER BY FirstName DESC

2. Get a list of orders (with order dates) that were processed by employees
who are not sales representatives:

SELECT [OrderID], [OrderDate]


FROM [Orders]
WHERE [EmployeeID] IN
(SELECT [EmployeeID] FROM [Employees]
WHERE [Title]<>'Sales Representative')

2. Using Sub-queries in the where clause –Exists

1. Return a list of customers who has orders shipped to UK

select CustomerID, CompanyName OR using join


from customers as a
where exists select CustomerID, CompanyName
( from customers, orders
select * from orders as b where CustomerID = CustomerID
where a.CustomerID = b.CustomerID and ShipCountry = 'UK'
and ShipCountry = 'UK'
)
3. Using Sub-queries in the where clause –Not Exists

1. Get the distinct names for products that are always ordered with quantity
greater than 10.

SELECT DISTINCT ProductName


FROM [Products]
WHERE NOT EXISTS
(SELECT * FROM [Order Details]
WHERE [Order Details].[ProductID]=[Products].[ProductID]
and QUANTITY<10);

2. Get the customer name and title for customers that have not placed any orders.

SELECT ContactName,ContactTitle
FROM Customers AS c
WHERE Not EXISTS(SELECT *
FROM [Orders] AS o
WHERE o.CustomerID = c.CustomerID)

Note:
• When using subquery in the where clause , take care when using operators ; If
the subquery returns more than one value you can’t use operator such as = , but
you may use the IN operator.
• (IN) predicate can either return TRUE, FALSE or NULL :
o TRUE is returned when the required value is NOT NULL and could be
found.
o FALSE is returned when the required value is NOT NULL and is NOT found
and the list DOES NOT contain NULL values
o NULL is returned when the required value is NULL, or when the required
values is NOT NULL and was not found in the list and the list contains at
least one NULL value
• EXISTS condition is considered "to be met" if the sub query returns at least one
row, it always returns TRUE or FALS
o TRUE as soon as it finds only a single matching row in the sub query
o FALSE, if it find none.
• NOT EXISTS will return TRUE only if no row is returned from the sub query.
4. Using Sub-queries in the where clause – “All”
1. Get the last name, all emplyees who were hired before all emplyees
working as ‘Sales Managers’ and ‘Inside Sales Coordinators’.

SELECT LastName
FROM Employees
where HireDate < ALL (SELECT HireDate
FROM Employees
WHERE Title IN ('Sales Manager', 'Inside Sales Coordinator'))

5. Using Subquery in FROM Clause “Represents a table”


1. Get the supplier name (contact name) and the supplied product name for
products having unit price less than 7. Fully optimize your query to
minimize the cost of accessing any unneeded columns and/or rows from
the relevant tables.

SELECT S.ContactName, P.ProductName


FROM (SELECT ContactName,SupplierID FROM Suppliers) AS S ,
(SELECT ProductName, SupplierID, UnitPrice FROM Products WHERE
UnitPrice < 7) AS P
Where S.SupplierID = P.SupplierID

Note:

• Mainly we use this way to shrink the size of the table and decrease the cost of
working with the whole table (considering all columns in it). So, we choose only the
set of columns we need from the table(s) related to our query.
• As shown in the above example, we can give an alias to the subquery and use it in
the main query.

You might also like