Module 3 - Nested Queries, division and views

Nested queries


Non-Correlated queries

Example

Find the IDs and names of stars who have NOT been in the movie with ID 28:

SELECT  M.starID, M.name
FROM     MovieStar M
WHERE  M.starID NOT IN
   (SELECT  S.starID
    FROM     StarsIn S
    WHERE  movieID=28
   );

Correlated Queries

Example

Find the names of departments that are managed by the same employee.

SELECT dName, mgrSSN 
FROM Department D1
WHERE mgrSSN IN 
  (SELECT mgrSSN 
   FROM Department D2
   WHERE D2.mgrSSN = D1.mgrSSN AND D2.dNumber <> D1.dNumber);

Subquery operators

Operator Description Example
IN Checked for set membership List the department names for departments which have a manager named “Jennifer”. alt text
ANY/ALL Compares with the set returned. These operations use operators including<,>,,,<><, >, \ge, \le, <> alt text
Single value operators Expression is compared with the value(s) returned Find the names and salaries of employees getting the minimum salary. alt text
operations include <,>,,,<><, >, \ge, \le, <>
EXISTS Tests the existence of data that meet the criteria of the subquery. EXISTS evaluates to true if the result of the correlated subquery is a non-empty set. Find movies that were the only movie produced that year. alt text

Division problem

alt text

Counting

“Find the movie star(s) who acted in at least all the movies produced in the year 1934.”

Relational Schema

A two step process:

  1. Count the number of movies in 1934
  2. Count the number of movies in 1934 that MoviesStar X acted in

STEP 1:

alt text

STEP 2:

alt text


Double negation

“Find the movie star(s) who acted in at least all the movies produced in the year 1934.”

  1. Find the negation of the statement - in this case, the blue region of the diagram. We want this section to be EMPTY and apply this negation through the use of a NOT EXISTS operation.
  2. Use a correlated inner query to compute the result
    • For instances where the blue is NOT NULL (empty) we will not return a result
    • For instances where the blue is NULL (and this is where both the green and the red is true) we will return a result

STEP 1:

alt text

STEP 2:


Views

CREATE VIEW DepEmpStatus as
SELECT  dNumber, dName, sex, COUNT(*) AS employeeNumber, AVG(salary) as avgSalary 
FROM  Department AS D
JOIN     Employee AS E ON D.dNumber= E.dNum
GROUP BY   dNum, sex; 

SELECT *
FROM DepEmpStatus;

Benefits of using views

Dropping views

Dropping a view does not affect any tuples from the underlying relation.

alt text