Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 46

SQL Queries – Part II

First Semester 2021-2022


Database Schema

Slide #-2
NESTED QUERIES
 A complete SELECT query, called a nested query , can be
specified within the WHERE-clause of another query, called the
outer query
 Many of the previous queries can be specified in an alternative
form using nesting.

Slide #-3
NESTED QUERIES (cont.)
Q1: List the last name of all employees whose salary is greater than the
salary of Smith.

SELECT Lname
FROM Employee
WHERE Salary > (Select Salary
From Employee
Where Lname = 'Smith');
Result
LNAME

---------------
Wong
Wallace
Narayan
Borg Slide #-4
NESTED QUERIES (cont.)
Query 2: List the last name of all employees who works in the
department managed by Wong.

SELECT Lname
FROM Employee
WHERE Lname NOT LIKE 'Wong' AND
Dno =(Select Dnumber
From Employee, Department
Where Ssn = Mgr_ssn AND Lname = 'Wong');
Result
LNAME

---------------
Smith
Narayan Slide #-5
NESTED QUERIES (cont.)
 ANY (or SOME) : The ANY test is used in conjunction with one
of the six SQL comparison operators ( =, !=, <, <=, >, >=) to
compare a single test value to a column of data values produced by
a subquery.
 To perform the test SQL uses the specified comparison operator to
compare the test value to each data value in the column, one at
time.
 If any of the individual comparisons yield a TRUE result, the ANY
test returns a TRUE result.

Slide #-6
NESTED QUERIES (cont.)

 ALL: Similar to the ANY test, the ALL test is used in conjunction
with one of the six SQL comparison operators ( =, !=, <, <=, >, >=)
to compare a single test value to a column of data values produced
by a subquery.
 To perform the test SQL uses the specified comparison operator to
compare the test value to each data value in the column, one at time.
 If all of the individual comparisons yield a TRUE result, the ALL
test returns a TRUE result.

Slide #-7
NESTED QUERIES (cont.)
Query 3:
Retrieve the names of all employees whose salary is greater than the
salary of all employees in department 5.
Solution:
SELECT LNAME, FNAME
FROM EMPLOYEE
WHERE SALARY > ALL (SELECT SALARY
FROM EMPLOYEE
WHERE DNO = 5);
LNAME FNAME
---------- ----------
Borg James
Result
Wallace Jennifer
Slide #-8
CORRELATED NESTED QUERIES
 If a condition in the WHERE-clause of a nested query references an
attribute of a relation declared in the outer query , the two queries are
said to be correlated
 The nested query is evaluated once for tuple in the outer query.
 Query 4:
Retrieve the name of each employee who has a dependent with the
same first name and same gender as the employee.

SELECT E.FNAME, E.LNAME


FROMEMPLOYEE AS E
WHERE E.SSN IN
(SELECT ESSN
FROM DEPENDENT AS D
WHERE E.FNAME = D.DEPENDENT_NAME
AND E.SEX = D.SEX);
Slide #-9
CORRELATED NESTED QUERIES (cont.)
 A query written with nested SELECT... FROM... WHERE... blocks
and using the = or IN comparison operators can always be
expressed as a single block query.
 For example, Query 4 may be written as in Query 4B
Query 4 B:
SELECT E.FNAME, E.LNAME
FROM EMPLOYEE E, DEPENDENT D
WHERE E.SSN=D.ESSN AND
E.FNAME=D.DEPENDENT_NAME
AND E.SEX = D.SEX;

Slide #-10
THE EXISTS FUNCTION
 EXISTS is used to check whether the result of a correlated nested
query is empty (contains no tuples) or not.
 The result of EXISTS is a Boolean value,

• TRUE if the nested query contains at least one tuple, or


• FALSE if the nested query does not contain any tuple.

 We can formulate Query 4 in an alternative form that uses EXISTS


as Q16B below.

Slide #-11
THE EXISTS FUNCTION
 Query 4: Retrieve the name of each employee who has a dependent
with the same first name and same gender as the employee.
 Query 4C:
SELECT E.FNAME, E.LNAME
FROM EMPLOYEE AS E
WHERE EXISTS
(SELECT *
FROM DEPENDENT AS D
WHERE E.SSN = D.ESSN AND
E.SEX = D.SEX AND
E.FNAME=DEPENDENT_NAME);

Slide #-12
THE EXISTS FUNCTION
 Query 5: Retrieve the names of employees who have no dependents.

SELECT FNAME, LNAME


FROM EMPLOYEE
WHERE NOT EXISTS
(SELECT *
FROM DEPENDENT
WHERE SSN=ESSN); Result
FNAME LNAME
---------- ----------
James Borg
Ahmed Jabbar
Alicia Zelaya
Ramesh Narayan
Joyce English

Slide #-13
THE EXISTS FUNCTION
 Query 6: List the names of managers who have at least one
dependent.

SELECT FNAME, LNAME


Result
FROM EMPLOYEE
WHERE EXISTS FNAME LNAME
(SELECT *
--------------- ---------------
FROM DEPENDENT
Franklin Wong
WHERE SSN=ESSN) Jennifer Wallace
AND EXISTS
(SELECT *
FROM DEPARTMENT
WHERE SSN=MGR_SSN);
Slide #-14
EXPLICIT SETS
 It is also possible to use an explicit (enumerated) set of values in
the WHERE-clause rather than a nested query
 Query 7: Retrieve the social security numbers of all employees who
work on project number 1, 2, or 3.
SELECT DISTINCT ESSN
FROM WORKS_ON
WHERE PNO IN (1, 2, 3);

ESSN
----------
123456789
Result 333445555
453453453
666884444 Slide #-15
EXPLICIT SETS
 It is also possible to use an explicit (enumerated) set of values in
the WHERE-clause rather than a nested query
 Query 7B: Retrieve the name of employees who work on project
number 1, 2, or 3.
SELECT DISTINCT Lname
FROM Employee, WORKS_ON
WHERE ESSN = SSN AND PNO IN (1, 2, 3);

Lname
----------
XXXX
Result YYYYY
ZZZZZ
WWWWW Slide #-16
Joined Tables in SQL
 Can specify a "joined relation" in the FROM-clause
 Allows the user to specify different types of joins:
• regular JOIN,
• NATURAL JOIN,
• LEFT OUTER JOIN,
• RIGHT OUTER JOIN,
• CROSS JOIN, etc)

Slide #-17
Regular Join
 Examples:
Query 8:
SELECTFNAME, LNAME, ADDRESS
FROM EMPLOYEE, DEPARTMENT
WHERE DNAME='Research' AND DNUMBER=DNO;

Can be written in SQL as in Query 8 B:


Query 8B:
SELECT FNAME, LNAME, ADDRESS
FROM (EMPLOYEE JOIN DEPARTMENT ON DNO = DNUMBER)
WHERE DNAME = ‘Research’;

Slide #-18
Natural Join
NATURAL JOIN
 In a NATURAL JOIN on two relations R and S, no join condition is
specified;
 An implicit EQUIJOIN condition for each pair of attributes with
the same name from R and S is created.
 If the names of the join attributes are not the same in the base
relations, it is possible to rename the attributes so that they match, and
then apply the NATURAL JOIN.
 In this case the AS construct can be used to rename a relation and all
its attributes in the FROM clause.
Slide #-19
Natural Join
 Query 8C:
SELECT FNAME, LNAME, ADDRESS
FROM (EMPLOYEE NATURAL JOIN DEPARTMENT
AS DEPT(DNAME, DNO, MSSN, MSDATE)
WHERE DNAME='Research’;

Slide #-20
Inner Join
 The default type of join is called inner join, where a tuple is
included in the result only if a matching tuple exists in the other
relation.
 For example in query Q8A, only employees who have a supervisor
are included in the result, an EMPLOYEE tuple whose value for
Super_ssn is NULL is excluded.
 Example:

Query 9: This query retrieve only employees with a supervisor


SELECT E.LNAME AS “Employee_name”,
S.Lname As “Supervisor_name”
FROM EMPLOYEE E, EMPLOYEE S
WHERE E.Super_ssn = S.ssn;

Slide #-21
OUTER JOIN
 If the user requires that all employees be included, an OUTER JOIN
must be used explicitly specifying the keyword OUTER JOIN in a
joined table as in Q8B.
 Q8B: This query retrieve all employees with or without a supervisor:
SELECT E.LNAME AS "Employee_name",
S.Lname As "Supervisor_name"
FROM (EMPLOYEE E LEFT OUTER JOIN EMPLOYEE S ON
E.Super_ssn = S.ssn);

Slide #-22
AGGREGATE FUNCTIONS
 Include COUNT, SUM, MAX, MIN, and AVG
 Query 19: Find the maximum salary, the minimum salary, and the
average salary among all employees.
Q19:
SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE;

MAX(SALARY) MIN(SALARY) AVG(SALARY)


Result ----------- ----------- -----------
55000 25000 35125

Slide #-23
AGGREGATE FUNCTIONS
 Query 20: Find the maximum salary, the minimum salary, and the
average salary among employees who work for the 'Research'
department.
Q20:
SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND DNAME='Research‘;

MAX(SALARY) MIN(SALARY) AVG(SALARY)


Result ----------- ----------- -----------
40000 25000 33250 Slide #-24
AGGREGATE FUNCTIONS

 Queries 21: Retrieve the total number of employees in the


company.
SELECT COUNT (*)
FROM EMPLOYEE;

Slide #-25
AGGREGATE FUNCTIONS

 Queries 22: Retrieve the total number of employees in the


'Research' department:
SELECT COUNT (*)
FROM EMPLOYEE, DEPARTMENT

WHERE DNO=DNUMBER AND DNAME='Research’;

Slide #-26
AGGREGATE FUNCTIONS
 Queries 23: Count the number of distinct salary values in the
database
Q23:

SELECT COUNT (DISTINCT SALARY)


FROM EMPLOYEE;

COUNT(DISTINCTSALARY)
Result ---------------------
6
Slide #-27
GROUPING

 In many cases,
• we want to apply the aggregate functions to subgroups of tuples
in a relation
• Each subgroup of tuples consists of the set of tuples that have the
same value for the grouping attribute(s)

 The function is applied to each subgroup independently

 SQL has a GROUP BY-clause for specifying the grouping


attributes, which must also appear in the SELECT-clause

Slide #-28
GROUPING
Query 24: For each department, retrieve the department number, the
number of employees in the department, and their average salary.
SELECT DNO, COUNT (*), AVG (SALARY)
FROM EMPLOYEE
GROUP BY DNO;

• In Q24, the EMPLOYEE tuples are divided into groups--each group having the
same value for the grouping attribute DNO.
• The COUNT and AVG functions are applied to each such group of tuples
separately.
• The SELECT-clause includes only the
• grouping attribute, and
• the functions to be applied on each group of tuples.
• A join condition can be used in conjunction with grouping.

Slide #-29
GROUPING
Query 24 Result
SELECT DNO, COUNT (*), AVG (SALARY)
FROM EMPLOYEE
GROUP BY DNO;

DNO COUNT(*) AVG(SALARY)


---- ---------- -----------
Result of Query 24 1 1 55000
4 3 31000
5 4 33250
Slide #-30
GROUPING
 Query 25: For each project, retrieve the project number, project
name, and the number of employees who work on that project.
SELECT PNUMBER, PNAME, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME;
-

PNUMBER PNAME COUNT(*)


-------- --------------- ---------------
1 ProductX 2
Result 2 ProductY 3
3 ProductZ 2
10 Computerization 3
20 Reorganization 3
30 Newbenefits 3 Slide #-31
THE HAVING-CLAUSE

 Sometimes we want to retrieve the values of these


functions for only those groups that satisfy certain
conditions
 The HAVING-clause is used for specifying a
selection condition on groups (rather than on
individual tuples)

Slide #-32
THE HAVING-CLAUSE
 Query 26: For each project on which more than two employees work ,
retrieve the project number, project name, and the number of employees
who work on that project.
SELECT PNUMBER, PNAME, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME
HAVING COUNT (*) > 2;

PNUMBER PNAME COUNT(*)


------- --------------- -------------
2 ProductY 3
Result 10 Computerization 3
20 Reorganization 3
30 Newbenefits 3 Slide #-33
Exercises
Exercise 1:

 List the names of managers who have at least one dependent.

Slide #-34
Exercises
Exercise 1 Solution:
 List the names of managers who have at least one dependent.

SELECT E.FNAME, E.LNAME


FROM EMPLOYEE E
WHERE EXISTS (SELECT *
FROM DEPENDENT
WHER E.SSN=ESSN)
AND
EXISTS (SELECT *
FROM DEPARTMENT
WHERE E.SSN=MGR_SSN);
Slide #-35
Exercises
Exercise #1 Another Solution:
 List the names of managers who have at least one dependent.

SELECT E.FNAME, E.LNAME


FROM EMPLOYEE E, DEPARTMENT D, DEPENDENT P
WHERE E.SSn = D.MGR_SSN AND E.SSN = P.ESSN
GROUP BY E.FNAME, E.LNAME
HAVING COUNt(E.SSN) >0;

Slide #-36
Exercises
Exercise 2:
 For each project, retrieve the project number, project name, and the
number of employees from department 5 who work on that project.

Slide #-37
Exercises
Exercise 2 Solution:
 For each project, retrieve the project number, project name, and the
number of employees from department 5 who work on that project.

SELECT PNUMBER, PNAME, COUNT (*)


FROM PROJECT, WORKS_ON, EMPLOYEE
WHERE PNUMBER=PNO AND SSN=ESSN AND DNO=5
GROUP BY PNUMBER, PNAME;

Slide #-38
Exercises
Exercise 3:
 Retrieve the name of each department and the total number of
employees in the department who make $30,000 or more.

Slide #-39
Exercises
Exercise 3 Solution:
 Retrieve the name of each department and the count of total number
of employees in the department who make $30,000 or more.

SELECT DNAME, COUNT(*)


FROM DEPARTMENT, EMPLOYEE
WHERE DNUMBER=DNO AND SALARY > 30,0000
GROUP BY DNAME;

Slide #-40
Exercises
Exercise 4:
 Retrieve the name of each department where the total number of
employees who make $30,000 or more are more than 2.

Slide #-41
Exercises
Exercise 4:
 Retrieve the name of each department where the total number of
employees who make $30,000 or more are more than 2.

SELECT DNAME, COUNT(*)


FROM DEPARTMENT, EMPLOYEE
WHERE DNUMBER=DNO AND SALARY > 30,0000
GROUP BY DNAME
HAVING COUNT(*) > 2;

Slide #-42
Exercises
Exercise 5:
 Retrieve the name of each department and the total number of
employees in the department who make $30,000 or more but only
for departments with more than five employees.

Slide #-43
Exercises
Exercise 5: Solution
 Retrieve the name of each department and the count of total number
of employees in the department who make $30,000 or more but only
for departments with more than five employees.

SELECT DNAME, COUNT(*)


FROM DEPARTMENT, EMPLOYEE
WHERE DNUMBER=DNO AND SALARY > 30,0000
AND DNO IN (SELECT DNO
FROM EMPLOYEE
GROUP BY DNO
HAVING COUNT(*) > 5)
GROUP BY DNAME;
Slide #-44
Exercises
Exercise 6:
 List the last name of all employees working on one or more projects
on which an employee with last name Smith is working.
Note: last name Smith should not appear in the result.

Slide #-45
Exercises
Exercise 6:
 List the last name of all employees working on one or more projects
on which an employee with last name Smith is working.
Note: last name Smith should not appear in the result.
Solution:
SELECT DISTINCT Lname
FROM Employee, Works_On
WHERE Lname != 'Smith' AND Ssn = Essn AND
Pno IN (SELECT Pno
FROM WORKS_ON, EMPLOYEE
WHERE ESSN = SSN AND LNAME = 'Smith');

Slide #-46

You might also like