1
Database Systems SQL: Advanced QueriesDatabase Systems SQL: Advanced Queries
2
Union, Intersection, and Except (2)Union, Intersection, and Except (2)
Find the names of those people who are either agraduate student or an instructor or both in CSdepartment.
    select Name from Student where DeptName='CS'
     union
     select Name from Instructor where DeptName='CS'
union removes duplicate rows.
union all keeps duplicate rows.
3
Union, Intersection, and Except (3)Union, Intersection, and Except (3)
Find the names of those who are both a graduate student and aninstructor in CS department.
select Name from Student where  DeptName='CS‘
intersect
select Name from Instructor where DeptName='CS‘
Find the names of those who are an instructor but not agraduate student in CS department.
select Name from Instructor where DeptName='CS'
except
select Name from Student where DeptName='CS'
4
Union, Intersection, and Except (5)Union, Intersection, and Except (5)
make a list of all project numbers for projects thatinvolve an employee whose last name is “Smith”,either as a worker or as a manager of the departmentthat controls the project.
(SELECT Distinct Pnumber
FROM PROJECT, Works-on, Employee
WHERE Pnumber = Pno AND ESSN = SSN AND Lname = “Smith”)
UNION
(SELECT PNumber
FROM Project, Department, Employee
WHERE Dnum=Dnumber AND MGRSSN=SSN AND Lname=“Smith”)
5
Comparisons Involving NULL
SQL allows queries that check if a value is NULL (missing orunknown or not applicable)
SQL uses IS or IS NOT to compare NULLs because itconsiders each NULL value distinct from other NULLvalues, so equality comparison is not appropriate .
Find all employees who have no managers.
select * from Employees
where Manager-SSN is null;
Find all employees who have a manager.
select * from Employees
where Manager-SSN is not null;
6
Null Values and Three Valued Logic
The result of any arithmetic expression involving null is null
E.g.  5 + null  returns null
Any comparison with null returns unknown (null)
E.g.  5 < null   or   null <> null    or    null = null
Three-valued logic using the truth value unknown:
OR(unknown or truetrue
 (unknown or falseunknown
(unknown or unknown)= unknown
AND(true and unknown)= unknown
 (false and unknown) = false
(unknown and unknown) = unknown
NOT(not unknown)= unknown
Result of where clause predicate is treated as false if itevaluates to unknown (null)
7
Null Values and Three Valued Logic
Eaxmple: Consider table Employees with the following data:
EmpIdName     Salary    Bonus
123Smith    25000      5000
234John     28000      null
select Name, Salary+Bonus Total fromEmployee
Result is:
      NameTotal
        Smith  30000
        John        null
 
8
NVL function
Use NVL function to convert null values
Format:   nvl(exp1, exp2)
 exp1 is a source value that may be null
 exp2 is the target value for converting null
Ex:
select name, salary + nvl(bonus, 0) Total
   from Employee
Result is:
      NameTotal
        Smith  30000
        John 28000
9
Using IN
Retrieve the social security numbers of allemployees who work on project number 1, 2, or 3;
SELECT DISTINCT ESSN FROM Works-on
WHERE PNO IN (1, 2, 3);
Find all students who are 20, 22, or 24 years old.
        select * from Students where age in (20, 22, 24);
not in is the opposite of in.
10
Nested Queries
A complete SELECT query, called a nested query , can bespecified within the WHERE-clause of another query, called theouter query
Many of the previous queries can be specified in an alternativeform using nesting
Retrieve the name and address of all employees who work forthe 'Research' department.SELECTFNAME, LNAME, ADDRESSFROM EMPLOYEEWHEREDNO IN(SELECT DNUMBER FROM DEPARTMENTWHERE DNAME='Research');
11
Nested Queries
Make a list of all project numbers for projects thatinvolve an employee whose last name is “Smith”,either as a worker or as a manager of the departmentthat controls the project.
select distinct Pnumber from Project
wherePnumber IN
(select pnumber from project, department, employee
where dnum=dnumber and MGRSSN=SSN
and Lname=‘Smith’)
OR
Pnumber IN
(select pno from works-on, employee
             where ESSN=SSN and Lname = ‘Smith’);
12
Nested Queries
Find the names of all students who take at least one courseoffered by the CS department.
Select Name from student s, enrollment e where s.SSN=e.SSNand e.cno in (select cno  from course where dept_name = 'CS')
The previous query is equivalent to:
(1) select Name from student s, snrollment e, course c where s.ssn =e.ssn and e.cno=c.cno and c.dept_name = 'CS’;
(2) select Name from Student where SSN in
           (select SSN from Enrollment where cno in
                (select cno from Course where Dept_Name='CS'));
13
Nested Queries
The previous query is a nested query. The queryoutside is an outer query and the query nested underthe outer query is an inner query. Multiple nestingsare allowed.
The semantics of the above query is to evaluate theinner query first and evaluate the outer query last.
Many nested queries have equivalent non-nestedversions.
14
Nested Queries
Example:  Consider the relations:
   Employee (SSN, Name, Age),
   Dependent (Name, Sex, ESSN)
Find the names of all employees who has a dependentwith the same name.
     select Name from Employee where Name in
          (select Name from Dependent  where ESSN = SSN)
15
Nested Queries
in accepts multi-column list.
Find all enrollments that have 25 years old students taking CScourses.
select * from enrollment where (SSN, Crs_noin
       (select s.SSN, c.crs_no from student s, course c wheres.age=25 and c.dept_name='CS');
Another way to write the query:
      select * from enrollment where
SSN in (select SSN from student where Age = 25)
         and
crs_no in (select crs_no from course where dept_name='CS');
16
Using ANY
There’s an alternate way of seeing if a value isIN some table
The evaluation of ANY expressions is notalways intuitive
Examples:
4 = ANY (1,2,3,4)
True, because it’s equal to the 4.
4 <> ANY (1,2,3,4)
True, because it’s not equal to the 1.
17
Using ANY
Find the names of those students who are 18 or younger andwhose GPA is higher than the GPA of any students who are 25 orolder.
        select Name from Student where age <= 18 and GPA > any
                (select GPA from Student where Age >= 25);
Other set comparison operators:
>any,  <any,  <=any,   >=any,  =any,  <>any
18
Using ALL
Similarly, we can use ALL to see how a value compares to all valuesin a table
Other set comparison operators:
>all,  <all,  <=all,  >=all,  =all,  <>all
Again, the evaluation of ALL expressions is not always intuitive
Examples:
4=ALL(1,2,3,4)
No, because it’s not equal to the 1.
4<>ALL(1,2,3,4)
Yes, because it’s not equal to the 1.
4=ALL(4,4,4,4)
Yes, because all of the values are 4.
19
Using ALL
Retrieve the names of employees whose salary isgreater than the salary of all the employees inDepartment 5
SELECT Lname, Fname  FROM Employee
where salary > ALL
      (select salary from employeewhere DNO=5);
20
Using ANY and ALL
=any is equivalent to in
<>any is not equivalent to not in.
<>all is equivalent to not in.
   Let x = a and S = {a, b}.  Then
x <> any S is true (x <> b) but
x not in S is false.
x <> all Sis also false (x <> b but x=a).
21
Correlated Nested Queries
If a condition in the WHERE-clause of a nested queryreferences an attribute of a relation declared in the outerquery , the two queries are said to be correlated.
The result of a correlated nested query is different for eachtuple (or combination of tuples) of the relation(s) the outerquery
Retrieve the name of each employee who has a dependentwith the same first name and same sex as the employee.SELECT  FNAME, LNAMEFROMEMPLOYEE EWHERESSN IN
(SELECT ESSN FROM DEPENDENT WHERE  ESSN = SSN  AND        FNAME = DNAME AND
        E.Sex = Sex);
22
Correlated Nested Queries
In the previous query, the nested query has a different resultfor each tuple  in the outer query
A query written with nested SELECT... FROM... WHERE...blocks and using the = or IN comparison operators canalways  be expressed as a single block query.
SELECT FNAME, LNAMEFROM EMPLOYEE E, DEPENDENT DWHERE SSN=ESSN ANDFNAME=DNAME AND
E.Sex = D.Sex;
23
The EXISTS Function
EXISTS is used to check whether the result of acorrelated nested query is empty (contains no tuples)or not.
We can formulate the previous query in analternative form that uses EXISTS as below:
 SELECTFNAME, LNAMEFROMEMPLOYEE EWHEREEXISTS
(SELECT FROMDEPENDENT WHERESSN=ESSN AND FNAME=DNAME AND
E.Sex = Sex);
24
The EXISTS Function
Retrieve the names of employees who have no dependents.SELECT  FNAME, LNAMEFROMEMPLOYEEWHERE NOT EXISTS
(SELECT * FROM DEPENDENT
WHERE SSN=ESSN);
The correlated nested query retrieves all DEPENDENT tuplesrelated to an EMPLOYEE tuple. If none exist , theEMPLOYEE tuple is selected
EXISTS is necessary for the expressive power of SQL
25
The EXISTS Function
Find all students who take at least one course.
       select * from Student s where exists
           (select * from Enrollment where SSN = s.SSN);
The previous query is equivalent to:
select distinct s.* from Student s, Enrollment e
           where s.SSN = e.SSN;
select * from Student where SSN in
                (select SSN from Enrollment);
26
The EXISTS Function
exists () is true if the set () is not empty.
exists () is false if the set () is empty.
not exists () is true if the set () is empty.
not exists () is false if the set () is not empty.
27
The EXISTS FunctionThe EXISTS Function
Find all students who do not take CS532.
  select * from Student s where not exists
       (select * from Enrollment where SSN=s.SSNand cno= 'CS532');
This query is equivalent to:
   select * from Student where SSN not in
        (select SSN from Enrollment
         where cno = 'CS532');
SQL function UNIQUE(Q)SQL function UNIQUE(Q)
Returns TRUE if there are no duplicate tuples in theresult of query Q
28
Joining Tables
Find the titles of all courses offered by departments located in building EB.
 Department(Name, Location)Dept (DName, Location)
 Course(CNo, Title, DName)
selectTitle
fromCourse join Department on Dname=Name
whereLocation = 'EB’;
or
select Title
 fromCourse natural join
Department As D(DName, Location, Chairman)
    whereLocation = 'EB'
or
selectTitle
fromCourse natural join Dept
whereLocation = 'EB'
29
Joining Tables
SELECTFNAME, LNAME, ADDRESSFROM EMPLOYEE, DEPARTMENTWHEREDNAME='Research' AND DNUMBER=DNO;
could be written as:SELECTFNAME, LNAME, ADDRESSFROM (EMPLOYEE JOIN DEPARTMENT ON DNUMBER=DNO)WHEREDNAME='Research’;
or as:SELECTFNAME, LNAME, ADDRESSFROM (EMPLOYEE NATURAL JOIN DEPARTMENT AS DEPT(DNAME, DNO, MSSN, MSDATE)WHEREDNAME='Research’
30
Retrieve pnumber, dnum, lname, bdate for employeesworking on projects located at “Stafford”.
SELECT PNUMBER, DNUM,LNAME, BDATEFROM((PROJECT JOIN
DEPARTMENT ON DNUM=DNUMBERJOIN
EMPLOYEE   ON MGRSSN=SSN )WHERE PLOCATION='Stafford’;
Joining Tables
31
Joining Tables
Employee(SSN, Name, Position, Pno)
Project(Pno, Title, Budget)
Find who works for which project.
select SSN, Name, Title
from Employee e join Project p
on e.Pno = p.Pno;
Identify also those who do not work for any project.
select SSN, Name, Title
from Employee e left outer join Project p
on e.Pno = p.Pno;
32
Joining Tables
Identify also those projects no one works for.
select SSN, Name, Title
  from Employee e right outer join
on e.Pno p.Pno;Project p on e.Pno p.Pno;
Identify even those who do not work for any projectand those projects no one works for:
select SSN, Name, Title
from Employees natural full joinProjects;
33
Aggregate FunctionsAggregate Functions
SQL supports five aggregate functions:
 
Name   Argum. type   Result type  Description
avg    numeric       numeric      average
count  any           numeric      count
min    char or num.  same as arg  minimum
max    char or num.  same as arg  maximum
sum    numeric       numeric      sum
34
Aggregate FunctionsAggregate Functions
Find the maximum salary, the minimum salary, and theaverage salary among all employees.SELECT  MAX(salary), MIN(salary), AVG(salary)FROMEMPLOYEE;
Find the maximum salary, the minimum salary, and theaverage salary among employees who work for the'Research' department.
SELECT MAX(salary), MIN(salary), AVG(salary)FROMEMPLOYEE, DEPARTMENTWHEREDNO=DNUMBER AND DNAME='Research‘;
35
Aggregate Functions
Retrieve the total number of employees in the company
SELECT  COUNT (*)  FROMEMPLOYEE;
Retrieve the number of employees in the 'Research' departmentSELECT  COUNT (*) FROMEMPLOYEE, DEPARTMENTWHEREDNO=DNUMBER AND DNAME='Research’;
Find the number of courses offered.
        select count(distinct Course_no) from Enrollment
Note that the above is different from
        select distinct count(Course_no)  from Enrollment
Find the average, the minimum and the maximum GPAs amongall students' GPAs.
select avg(GPA), min(GPA), max(GPA) from Student
36
Aggregate Functions
Find the SSNs and names of all students who take 5 or morecourses.
select SSN, Name from Students s
where 5 <= (select count(*) from enrollment where ssn = s.ssn);
Count the number of distinct salary values in the database.
SELECT COUNT(DISTINCT Salary) FROM Employee;
Retrieve the names of all employees who have two or moredependents.
SELECT Lname, Fname FROM Employee
where (select count(*) from dependent where ssn= essn) >= 2;
37
Aggregate Functions
Find the number of students who are 17 years old.
       select count(*) from Student  where Age = 17
The above last query is equivalent to
      select count(SSN) from Students where Age = 17
but may not be equivalent to
      select count(Name) from Students where Age=17
Aggregate functions, except count(*), ignore null values.
38
Group By & Having Clause
In many cases, we want to apply the aggregate functions tosubgroups of tuples in a relation
Each subgroup of tuples consists of the set of tuples that havethe same value  for the grouping attribute(s)
The function is applied to each subgroup independently
SQL has a GROUP BY-clause for specifying the groupingattributes, which must also appear in the SELECT-clause
39
Grouping
For each department, retrieve the department number, thenumber of employees in the department, and their averagesalary.
SELECT DNO, COUNT (*), AVG (SALARY)FROMEMPLOYEEGROUP BYDNO;
the EMPLOYEE tuples are divided into groups--each grouphaving the same value for the grouping attribute DNO
The COUNT and AVG functions are applied to each suchgroup of tuples separately
The SELECT-clause includes only the grouping attribute andthe functions to be applied on each group of tuples
A join condition can be used in conjunction with grouping
40
Grouping
For each project, retrieve the project number, project name,and the number of employees who work on that project.SELECT PNUMBER, PNAME, COUNT (*)FROMPROJECT, WORKS_ONWHEREPNUMBER=PNOGROUP BYPNUMBER, PNAME;
In this case, the grouping and functions are applied after  thejoining of the two relations
41
Grouping
Find the average GPA for students of different age groups.
       select Age, avg(GPA)  from Students group by Age;
One tuple will be generated for each distinct value of age.
STUDENTS                     RESULTSTUDENTS                     RESULT
SSN        Name   Age   GPA        Age   avg(GPA)SSN        Name   Age   GPA        Age   avg(GPA)
123456789  John   19    3.6        19      3.7123456789  John   19    3.6        19      3.7
234567891  Tom    20    3.2        20      3.5234567891  Tom    20    3.2        20      3.5
345678912  Tom    19    3.8        21      2.8345678912  Tom    19    3.8        21      2.8
345678912  Bill   21    2.8345678912  Bill   21    2.8
345678912  Mary   20    3.8345678912  Mary   20    3.8
42
Grouping
When group by is used, each attribute in the select clause musthave a single atomic value for each group of common group byvalues.
Each attribute in the select clause should be either a groupingattribute or an attribute on which a set function is applied.
Every grouping attribute should be listed in the select clause.
The following is an illegal query:
select Age, SSN, avg(GPA) from Students group by Age
43
Grouping
Find the SSN, name and the number of credit hourseach student still needs to graduate.
Course(CNo, Title, Dept_Name, CreditHour)
Enrollment(SSN, CNo, Grade, Semester)
Assume that each student needs 120 credit hours tograduate.
select ssn, name, 120-sum(credithour) CreditNeeded
from Student s, Enrollment e, Course c
where s.ssn=e.ssn and e.CNo=c.CNo
group by s.ssn, name
44
The Having Clause
Sometimes we want to retrieve the values of thesefunctions for only those groups that satisfy certainconditions
Having is used in conjunction with group by in thecases where the groups must satisfy a condition toappear in the result.
The HAVING-clause is used for specifying aselection condition on groups (rather than onindividual tuples)
Conditions on aggregate functions are specified inthe having clause.
45
The Having Clause
For each project on which more than two employees work ,retrieve the project number, project name, and the number ofemployees who work on that project.SELECT       PNUMBER, PNAME, COUNT (*)FROM      PROJECT, WORKS_ONWHERE      PNUMBER=PNOGROUP BY   PNUMBER, PNAMEHAVING      COUNT (*) > 2;
Find the number of students of each age group and outputonly those groups having more than 50 members.
select Age, count(*) from Students
group by Age
having count(*) > 50;
46
The Having Clause
For each department having more than fiveemployees, retrieve the department name and thenumber of employees making more than $40000.
SELECT Dname, COUNT(*)
FROM Department, Employee
WHERE Dnumber = DNO and Salary > 40000 ANDDNO IN (Select DNO FROM Employee
                        Group by DNO Having COUNT(*)>5)
GROUP BY Dname;
47
Summary of SQL Queries
A query in SQL can consist of up to six clauses, butonly the first two, SELECT and FROM, aremandatory.
The clauses are specified in the following order:SELECT<attribute list>FROM<table list>[WHERE<condition>][GROUP BY <grouping attribute(s)>][HAVING<group condition>][ORDER BY <attribute list>]
48
Evaluation of a six-clause query
1.  Form all combinations of tuples from the relations in the from clause(Cartesian product).
2. Among all the tuples generated in step 1, find those that satisfy theconditions in the where clause.
3. Group the remaining tuples based on the grouping attributes.
4.  Among all the tuples generated in step 3, find those that satisfy theconditions in the having clause.
5.  Using the order by clause to order the tuples produced in step 4.
6.  Project on the desired attribute values as specified in the select clause.
49
SQL: Example 1
Find the average GPAs of students of different agegroupsOnly students younger than 35 are consideredand only groups with the average GPAs higher than 3.2are listed. The listing should be in ascending agevalues.
select Age, avg(GPA)
from Student
where Age < 35
 group byAge
havingavg(GPA) > 3.2
order byAge
50
SQL: Example 2
Consider two tables:
 Agents(aid, aname, city, percent)
 Orders(ordno, month, cid, aid, pid, qty, dollars)
Find the aid and total commission of each agent. Anagent’s total commission is computed based onhis/her commission rate and total sale (in dollars).
select a.aid, a.percent*sum(dollars) as commission
  from agents a, orders o
  where a.aid = o.aid
  group by a.aid, a.percent;
51
The Drop CommandThe Drop Command
DROP SCHEMA COMPANY CASCADE;
the schema and all its elements  (tables, views, domaindefinitions … etc.) are also deleted.
DROP SCHEMA COMPNAY RESTRICT;
the schema will be deleted if it has no elements. If it hasany element the drop schema statement  will not beexecuted.
DROP TABLE DEPENDENT CASCADE;
The table dependent and all other elements that referencethe dependent table are also deleted (e.g. foreign keys andviews).
DROP TABLE DEPENDENT RESTRICT;
The table is deleted only if it is not referenced in anyconstraint (foreign key definitions in other tables, views).
52
ALTER TABLEALTER TABLE
Add attributes to base relations:
ALTER TABLE COMPANY.EMPLOYEE ADD columnJOB VARCHAR(12);
Drop  a column:
ALTER TABLE COMPANY.EMPLOYEE DROPcolumn ADDRESS CASCADE;
all views and constraints that reference this column areautomatically deleted.
ALTER TABLE COMPANY.EMPLOYEE DROPcolumn ADDRESS RESTRICT;
the address attribute won’t be deleted if it is beingreferenced by other schema elements.
53
ALTER TABLEALTER TABLE
Drop the default value of an attribute:
ALTER TABLE COMPNAY.DEPARTMENT altercolumn MGRSSN DROP DEFAULT;
Change the default value of an attribute:
ALTER TABLE COMPANY.DEPARTMENT ALTERcolumn MGRSSN SET DEFAULT “333445555”;
Drop constraintsDrop constraints
ALTER TABLE COMPANY.EMPLOYEE DROPCONSTRAINT EMPSUPERFK CASCADE;
Add constraintsAdd constraints
ALTER TABLE COMPANY.EMPLOYEE ADDCONSTRAINT ……;
54
ALTER TABLEALTER TABLE
alter table Student add column Addressvarchar2(40);
 
alter table Student add constraintunique(Address);
 
not null cannot be specified for newly added attributes.
DDL statements (create, alter, drop, truncate,etc), once executed, are irreversible!   NO UNDO!!!
55
Union, Intersection, and Except (1)Union, Intersection, and Except (1)
SQL supports three set operations:SQL supports three set operations:
union, intersect, minus
Union compatibility is required.Union compatibility is required.
Consider the following two relations:Consider the following two relations:
Students(SSN, Name, GPA, GRE, DeptName)
Instructors(SSN, Name, Office, DeptName)