Chapter 5 6e & 8 5e: Complex SQL CSE 4701 Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut 191 Auditorium Road, Box U-155 Storrs, CT 06269-3155 steve@engr.uconn.edu http://www.engr.uconn.edu/~steve (860) 486 - 4818 About one third of these slides are being used with the permission of Dr. Ling Lui, Associate Professor, College of Computing, Georgia Tech. About one-half of these slides have been adapted from the AWL web site for the textbook. Chapter 5-1 Variety of Complex SQL Queries CSE 4701 Nested Queries Grouping and Aggregation Order by and Having Views Sets Tuple Variable Other Complex Queries and Operations Chapter 5-2 Recall Earlier Query 1 CSE 4701 Query 1: Retrieve Name and Address of all Employees who work for the 'Research' Department SELECT FNAME, MINIT, LNAME, ADDRESS, DNAME FROM EMPLOYEE, DEPARTMENT WHERE DNAME='Research' AND DNUMBER=DNO What Action is Being Performed? Chapter 5-3 Nested Queries CSE 4701 SQL SELECT Nested Query is Specified within WHERE-clause of another Query (the Outer Query) Query 1A: Retrieve the Name and Address of all Employees who Work for the 'Research' Department SELECT FNAME, LNAME, ADDRESS FROM EMPLOYEE WHERE DNO IN (SELECT DNUMBER FROM DEPARTMENT WHERE DNAME='Research' ) Note: This Reformulates Earlier Query 1 (not in book) Chapter 5-4 How Does Nested Query Work? CSE 4701 The Nested Query Selects Number of 'Research' Dept. The Outer Query Selects an EMPLOYEE Tuple If Its DNO Value Is in the Result of Either Nested Query IN represents Set Inclusion of Result Set We Can Have Several Levels of Nested Queries SELECT FNAME, LNAME, ADDRESS FROM EMPLOYEE Inner Query Returns WHERE DNO IN Relation of DNUMBER (SELECT DNUMBER D1, D2, etc. FROM DEPARTMENT WHERE Dname=’Research' ) Chapter 5-5 Correlated Nested Queries CSE 4701 When WHERE-clause of a Nested Query References an Attribute of a Relation Declared in the Outer Query Query 16: Retrieve the Name of each Employee who has a Dependent with the Same First Name as the Employee SELECT E.FNAME, E.LNAME Inner Query Returns FROM EMPLOYEE AS E Relation a set of WHERE E.SSN IN ESSNs for All Emps (SELECT ESSN that have Dependents FROM DEPENDENT with the same FNAME WHERE ESSN=E.SSN AND E.FNAME=DEPENDENT_NAME) Note: This Differs Slightly from 16 in book. Chapter 5-6 Query Equivalence CSE 4701 Query 16: SELECT E.FNAME, E.LNAME FROM EMPLOYEE AS E WHERE E.SSN IN (SELECT ESSN FROM DEPENDENT WHERE ESSN=E.SSN AND E.FNAME=DEPENDENT_NAME) Query 16A: SELECT E.FNAME, E.LNAME FROM EMPLOYEE E, DEPENDENT D WHERE E.SSN=D.SSN AND E.FNAME=D.DEPENDENT_NAME Chapter 5-7 EXISTS Nested Queries CSE 4701 EXISTS checks Whether the Result of a Correlated Nested Query is Empty (contains no tuples) or not Query 16B: Retrieve the Name of each Employee who has a Dependent with the Same First Name as the Employee Inner Query Returns SELECT FNAME, LNAME Is True if there is FROM EMPLOYEE At least one match. WHERE EXISTS (SELECT * Can there be 2 matches? FROM DEPENDENT WHERE SSN=ESSN AND FNAME=DEPENDENT_NAME) There is a analogous NOT EXISTS Chapter 5-8 NULLS in SQL Queries CSE 4701 SQL Allows Queries that Check if a value is NULL (Missing or Undefined or not Applicable) SQL uses IS or IS NOT to compare NULLs since it Considers each NULL value Distinct from other NULL Values, so Equality Comparison is not Appropriate Query 18: Retrieve the names of all employees who do not have supervisors. SELECT FNAME, LNAME FROM EMPLOYEE WHERE SUPERSSN IS NULL Why Would Such a Capability be Useful? Downloading/Crossloading a Database Promoting a Attribute to PK/FK Chapter 5-9 Aggregate Functions in SQL Queries CSE 4701 Query 19: Find Maximum Salary, Minimum Salary, and Average Salary among all Employees SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY) FROM EMPLOYEE Query 20: Find maximum and Minimum Salaries among 'Research' Department Employees SELECT MAX(SALARY), MIN(SALARY) FROM EMPLOYEE, DEPARTMENT WHERE DNAME='Research' AND DNUMBER=DNO What Does Query 22 Do? SELECT COUNT(*) FROM EMPLOYEE, DEPARTMENT WHERE DNAME='Research' AND DNUMBER=DNO Chapter 5-10 Grouping in SQL Queries CSE 4701 In Many Cases, We Want to Apply the Aggregate Functions to Subgroups of Tuples in a Relation Each Subgroup of Tuples is Set of Tuples that Have the Same Value for the Grouping Attribute(s) Function is Applied to Each Subgroup Independently Query 24: For Each Department, Retrieve the DNO, Number of Employees, and Their Average Salary SELECT DNO, COUNT (*), AVG (SALARY) FROM EMPLOYEE GROUP BY DNO Chapter 5-11 Grouping in SQL Queries CSE 4701 Query 24: For Each Department, Retrieve the DNO, Number of Employees, and Their Average Salary SELECT DNO, COUNT (*), AVG (SALARY) FROM EMPLOYEE GROUP BY DNO EMPLOYEE tuples are Divided into Groups; each group has the Same Value for Grouping Attribute DNO COUNT and AVG functions are applied to each Group of Tuples Aeparately SELECT-clause Includes only the Grouping Attribute and the Functions to be Applied on each Tuple Group Chapter 5-12 Results of Query 24: CSE 4701 SELECT DNO, COUNT (*), AVG (SALARY) FROM EMPLOYEE GROUP BY DNO Chapter 5-13 Joins and Grouping in SQL Queries CSE 4701 A Join Condition can be used in Conjunction with Grouping Query 25: For each Project, Retrieve its Number, Name, and Number of Employees working on Project SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ON WHERE PNUMBER=PNO GROUP BY PNUMBER, PNAME In this case, the Grouping and Functions are Applied after the Joining of the two Relations Chapter 5-14 The HAVING Clause in SQL Queries CSE 4701 In Some Cases, we want to retrieve values of Functions for only those Groups that Satisfy Certain Condition(s) The HAVING-clause is used for Specifying a Selection Condition on Groups (rather than Individual Tuples) Query 26: For each Project on which more than two employees work, Retrieve its Number, Name, and Number of Employees working on Project project SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ON WHERE PNUMBER=PNO GROUP BY PNUMBER, PNAME HAVING COUNT (*) > 2 Chapter 5-15 Results of Query 26: After Applying the WHERE/GROUP BY Clauses Two Groups Not Selected Based on Having Constraint CSE 4701 Chapter 5-16 Results of Query 26: After Applying the HAVING Clause Condition CSE 4701 3 3 3 3 Chapter 5-17 Substring Comparison in SQL Queries CSE 4701 In Regard to Strings, Most DBMSs Support SQL Queries for Exact, Near, and Starts with Matching LIKE is Used to Compare Partial Strings '%' (or '*') Replaces an Arbitrary # of characters '_' replaces a single arbitrary character Query 12: Retrieve all Employees whose Address is in Houston, Texas. SELECT FNAME, LNAME FROM EMPLOYEE WHERE ADDRESS LIKE '%Houston,TX% ' Houston, TX can be anywhere within the ADDRESS VAR CHAR String Chapter 5-18 Substring Comparison in SQL Queries CSE 4701 The LIKE Operator Allows us to get Around the Fact that each Value is Considered Atomic and Indivisible SQL: Character String Attribute values are not Atomic Query 12A: Retrieve all employees who were born during the 1950s. SELECT FNAME, LNAME FROM EMPLOYEE WHERE BDATE LIKE ' __5_______' There are two “_” before 5 and seven “_” after 5 Chapter 5-19 Arithmetic Operations in SQL Queries CSE 4701 Standard Arithmetic Operators '+', '-'. '*', and '/' can be Applied to Numeric Values in an SQL Query Result Query 13: Show the Effect of Giving all Employees who work on the 'ProductX' project a 10% raise. SELECT FNAME, LNAME, 1.1*SALARY FROM EMPLOYEE, WORKS_ON, PROJECT WHERE SSN=ESSN AND PNO=PNUMBER AND PNAME='ProductX' Chapter 5-20 ORDER BY Clause in SQL Queries CSE 4701 ORDER BY used to Sort the Tuples in a Query Result based on the Values of one or More Attribute(s) Query 15: Retrieve a list of Employees and the Projects each works in, ordered by Dept., and within each Dept., alphabetically by Employee last name SELECT FROM WHERE ORDER BY DNAME, LNAME, FNAME, PNAME DEPARTMENT, EMPLOYEE, WORKS_ON, PROJECT DNUMBER=DNO AND SSN=ESSN AND PNO=PNUMBER DNAME, LNAME Default is Ascending - Can be ASC/DESC as we’ll see in a Later Example Chapter 5-21 Let’s Jump to In Class Exercises CSE 4701 Chapter 5-22 SQL Support for Views CSE 4701 Views are Part of the SQL DDL Abstracting from Conceptual to External Schema View Hides the Details One or More Tables in Conceptual Schema May be Combined (in Part) to Form a View Don’t Include FKs and Other Internal Attributes Typically, View is Formed by Join of Two or More Relations Utilizing FKs, PKs, etc. As a Result - View is Independent Once Formed - View Static/Unchangeable to Insulate User Applications from Conceptual Schema Similar in Concept/Intent to “Public Interface” Chapter 5-23 SQL View Definition CSE 4701 Features of Views View Represents a Restricted Portion (Rows, Columns) of a Relation - External Schema in SQL View is Virtual Table View (Not Stored) and Must be Re-evaluated Every Time - Dynamic Like Relation, a View Can Be Deleted at Any Time Attributes Can Be Renamed in View CREATE VIEW PQ(P#, SUMQTY) AS SELECT P#, SUM(QTY) FROM SP GROUP BY P#; Reasons for Views Security Increasing Application-Data Independence Chapter 5-24 View Definition in Ongoing Example CSE 4701 First View: Attribute Names are Inherited CREATE VIEW WORKS_ON1 AS SELECT FNAME, LNAME, PNAME, HOURS FROM EMPLOYEE, PROJECT, WORKS_ON WHERESSN=ESSN AND PNO=PNUMBER ; Second View: View attribute names are Aliased via a one-to-one Correspondence with the SELECT-clause CREATE VIEW DEPT_INFO (DEPT_NAME, NO_OF_EMPS, TOTAL_SAL) AS SELECT DNAME, COUNT (*), SUM (SALARY) FROM DEPARTMENT, EMPLOYEE WHERE DNUMBER=DNO GROUP BY DNAME ; Chapter 5-25 Queries on Views CSE 4701 Retrieve the Last Name and First Name of All Employees Who Work on 'ProjectX'. SELECT PNAME, FNAME, LNAME FROM WORKS_ON1 WHERE PNAME='ProjectX' ; Without the View WORKS_ON1, this Query Specification Would Require Two Join Conditions A View Can Be Defined to Simplify Frequently Occurring Queries DBMS Keeps the View Up-to-date if the Base Tables on Which the View is Defined are Modified Hence, the View is Realized at the Time we Specify a Query on the View Chapter 5-26 What is View Update Problem? CSE 4701 Retrieval over View Mirrors a Retrieval over Relation However, Update over View may cause Problems! In general, a View Update may Introduce Ambiguity when there is more than one way to Update Underlying Relations Consider the view PQ Created Below: CREATE VIEW PQ(P#, SUMQTY) AS SELECT P#, SUM(QTY) FROM SP GROUP BY P#; Try to Change the Total Quantity SUMQTY of P1 in PQ from “30” to “40” Why Does a view Update Problem occur? Chapter 5-27 The Book Example - DDL - Create Tables CSE 4701 Create a Table in the MY_BOOK_DB Schema: What do ISBNNUMBER and PUBLISHERID Represent? CREATE TABLE BOOK_CATALOG (ISBN ISBNNUMBER NOT NULL, TITLE VARCHAR(25), AUTHORS VARCH(100), ... PUBLISHER PUBLISHERID, PRIMARY KEY (ISBN) FOREIGN KEY (PUBLISHER) REFERENCES PUBLISHING_HOUSE(NAME); Chapter 5-28 DDL - Create Tables (continued) CSE 4701 CREATE TABLE PUBLISHING_HOUSE (PUB_ID PUBLISHERID NOT NULL, PUB_NAME VARCHAR(50) LOC CITYNAME CONTACT ADDRESS, UNIQUE(PUB_NAME, LOC); CREATE TABLE ORDER (ISBN ISBNNUMBER NOT NULL, PUBLISHER PUBLISHERID DATE DATE NOT NULL, PRIMARY KEY(ISBN, PUBLISHER), FOREIGN KEY ISBN REFERENCES BOOK_CATALOG(ISBN), FOREIGN KEY PUBLISHER REFERENCES PUBLISHING_HOUSE(PUB_ID)); Chapter 5-29 DDL - Change Table Structure Add a Column to a Table: CSE 4701 ALTER TABLE BOOK ADD PRICE DECIMAL(7,2), ADD MEMBER_DISCOUNT, DEFAULT 5; No DEFAULT Implies NULL Values for all Tuples Drop a Column from a table ALTER TABLE BOOK DROP PRICE RESTRICT (or CASCADE); Restrict: Drop Operation Fails if Column is Referenced Cascade: Drop Operation Removes Referencing View and Constraint Definitions Chapter 5-30 Views Basis of APIs CSE 4701 WSDL, SOAP, REST, etc. View Presents a Limited Picture of the DB Defines Data Available to Different User Groups Applications (web or mobile) Other Systems (for Interoperability/Sharing) Most Typically Read-Based Views Update-Based Views Carefully Define Insure that Updates Don’t Alter Consistency May Limit What Chapter 5-31 Views in Medical Domain CSE 4701 Prescription Object has Multiple Views MD/Prescriber Ability to Write the Script with Drug, Dosage, Instructions, etc. Pharmacist -Fill Prescription (Drug dispensed) Ability to Substitute Generic for Brand A Refill Reduces Future Availability Patient Submit Script to Pharmacy/Insurance Insurer See Drug Dispensed, Script, Approve Payment Chapter 5-32 Other SQL Query Examples CSE 4701 Homework 2 Spring 2015 Book Database Employee/Project/Department Database Chinook Northwind Chapter 5-33 Another Set of Examples- Book DB BOOK(ISBN, TITLE,AUTHORS,PRICE,PUBLISHER,YEAR) ORDER(ISBN, CUST_NAME, LOC, DATE,WEEKDAY) Find the books Written by Maier CSE 4701 SELECT TITLE, ISBN FROM BOOK; WHERE AUTHOR LIKE ‘%MAIER’ ; Find ISBN of the Books Whose Price is at Least 5% less than the Average Price of the Books by Maier SELECT ISBN, PRICE FROM BOOK WHERE PRICE*(1-0.05) < SELECT AVG(PRICE) FROM BOOK WHERE AUTHORS LIKE “%Maier”; Chapter 5-34 Other SQL Search: String Matching CSE 4701 Wildcard: %: Matches any Substring _: Matches any Character SELECT * FROM BOOK WHERE PUBLISHER LIKE “%IEEE%”; “%can%” Matches American, Canada, Scandinavian, ... “Ca%” Matches Canada, Canadian, ... “ %” Matches any string with at least two characters Chapter 5-35 Other SQL Queries CSE 4701 Find ISBN and Price of Books Published by ACM SELECT ISBN, PRICE FROM BOOK WHERE PUBLISHER=“ACM”; Find ISBN and price for all books ordered from Atlanta with a price over $50 SELECT ISBN, PRICE FROM BOOK, ORDER WHERE BOOK.ISBN = ORDER.ISBN AND ORDER.LOC=‘ATL’ AND PRICE > 50.00; Note the Distinguishing Between Attributes with Same Name in Different Tables (TableName.AttributeName) Chapter 5-36 Using Tuple Variables CSE 4701 Tuple Variables Simplify Query Since Don’t Need to Repeat the Entire Table Name Find ISBN and Price for all Books ordered from Atlanta with a price over $50 SELECT B.ISBN, B.PRICE FROM BOOK B, ORDER O WHERE B.ISBN = O.ISBN AND O.LOC=‘ATL’ AND B.PRICE > 50.00; Also Useful if Relation is Used “twice” in a Query: SELECT B1.ISBN, B1.TITLE, B1.AUTHORS FROM BOOK B1, BOOK B2 WHERE B1.PRICE > B2.PRICE AND B2.ISBN = “111001100”; Chapter 5-37 Ordering Results CSE 4701 Order by Clause Sorts the rows in a Query Result in Ascending (asc) or Descending (desc) Order Find all books Published by ACM in the Ascending order of Price and Descending order of year SELECT * FROM BOOK WHERE PUBLISHER LIKE “ACM%” ORDER BY PRICE ASC, YEAR DESC; Questions: What Does “*” Indicate? What Does ACM% Retrieve? Chapter 5-38 Set Operations Find books written by Mary or Lisa SELECT * FROM BOOK WHERE AUTHORS LIKE “LISA%” UNION SELECT * FROM BOOK WHERE AUTHORS LIKE “MARY%”; CSE 4701 SELECT * FROM BOOK WHERE AUTHORS LIKE “LISA%” OR AUTHORS LIKE “MARY%”; UNION, INTERSECT, EXCEPT UNION ALL, INTERSECT ALL, and EXCEPT ALL Preserve Duplicates Chapter 5-39 Built-in Aggregate Functions CSE 4701 Count (COUNT), Sum (SUM), Average (AVG), Minimum (MIN), Maximum (MAX) Count Books Ordered on 2/16 SELECT COUNT( *) FROM ORDER WHERE ORDER.DATE = “2/16/2000”; Find the Average Price of Books by each Publisher SELECT PUBLISHER, AVG(PRICE) FROM BOOK GROUP BY PUBLISHER; Chapter 5-40 Built-in Aggregate Functions Find the Average Book Price of all Publishers that have Published more than 1000 Books SELECT PUBLISHER, AVG(PRICE) FROM BOOK GROUP BY PUBLISHER HAVING COUNT (ISBN) >= 1000; Find the Highest Priced book(s) by Maier SELECT ISBN, MAX(PRICE) FROM BOOK WHERE AUTHORS LIKE “%Maier%”; CSE 4701 Chapter 5-41 Nested Subqueries CSE 4701 Nested Subqueries Allow us to Ask More Complex Questions Regarding the Database Content Queries are Nested and Involve Set Relationships Relationships Supported Include: Set Membership: IN, NOT IN Set Comparison (=, <, <=, >, >=, <>) ALL (=, <, <=, >, >=, <>) SOME Test Empty Relation: EXISTS, NOT EXISTS Let’s see Some Examples… Chapter 5-42 Set Membership: IN, NOT IN CSE 4701 Find Title of the Books Ordered on Mondays SELECT DISTINCT TITLE FROM BOOK WHERE ISBN IN (SELECT ISBN FROM ORDER WHERE WEEKDAY = “MON”); Find Titles of Books ordered on Wednesday to Friday SELECT DISTINCT ISBN FROM BOOK WHERE WEEKDAY NOT IN (“MON”, “TUE”); Chapter 5-43 Set Comparison CSE 4701 Operators (=, <, <=, >, >=, <>) ALL (=, <, <=, >, >=, <>) SOME Find ISBN of Books Published by ACM, which are Cheaper than all Books Ordered by Smith SELECT ISBN FROM BOOK WHERE PUBLISHER LIKE “%ACM%” AND PRICE < ALL (SELECT B.PRICE FROM BOOK B, ORDER O WHERE CUST_NAME LIKE “%SMITH%” AND B.ISBN = O.ISBN); Chapter 5-44 EXISTS, NOT EXISTS CSE 4701 Find ISBN of Books with a Price so low That There is not any Cheaper Books from ACM SELECT B.ISBN FROM BOOK B WHERE B.PUBLISHER LIKE “%ACM%” AND NOT EXISTS (SELECT T.ISBN FROM BOOK T WHERE T.PUBLISHER LIKE “%ACM%” AND T.PRICE < B.PRICE); Chapter 5-45 Delete and Update CSE 4701 Cancel all orders by Mary on 2/17/2000 DELETE FROM BOOK WHERE DATE=2000-02-17 AND ISBN IN (SELECT ISBN FROM ORDER WHERE CUST_NAME LIKE “%Mary%”); Update all Orders for Customers on 2/15/2002 by giving a discount of 5% UPDATE ORDER SET PRICE = PRICE * (1-0.05) WHERE DATE=2002-02-50; Chapter 5-46 View Concepts/Examples CSE 4701 REM updatable view CREATE VIEW LOW-PRICE-BOOKS AS SELECT * FROM BOOKS WHERE PRICE<50.00; REM moves row outside view UPDATE LOW-PRICE-BOOKS SET PRICE = 60.00 WHERE PUBLISHER LIKE “%ACM%”; REMcreate row outside view INSERT INTO LOW-PRICE-BOOKS VALUES (“1010110022”, ”Java Beans”, “Smith”, 45, ”ACM”); REM prevents updates outside the view CREATE VIEW LOW-PRICE-BOOKS AS SELECT * FROM BOOK WHERE PRICE<50.00 WITH CHECK OPTION; Chapter 5-47 Homework 3 from Spr 2015 CSE 4701 Problem 6.18 from the 6th edition done in SQL and NOT relational expressions Chapter 5-48 Problem 6.18 in 6th edition CSE 4701 a. How many copies of the book titled The Lost Tribe are owned by the library branch whose name is ‘Sharpstown’? SELECT NoOfCopies FROM ( (BOOK NATURAL JOIN BOOK_COPIES ) NATURAL JOIN LIBRARY_BRANCH ) WHERE Title='The Lost Tribe' AND BranchName='Sharpstown’ BaB= (BOOKCOPIES * (Title=‘The Lost Tribe’ (BOOK))) ) BookId Ans = No_Of_Copies( (BranchName=‘Sharpstown’ (LIBRARY-BRANCH)) * BaB) BranchID Chapter 5-49 Problem 6.18 in 6th edition CSE 4701 b. How many copies of the book titled The Lost Tribe are owned by each library branch? SELECT BranchName, NoOfCopies FROM ( (BOOK NATURAL JOIN BOOK_COPIES ) NATURAL JOIN LIBRARY_BRANCH ) WHERE Title='The Lost Tribe' CaB = BOOKCOPIES * LIBRARY_BRANCH) BranchId Ans = BranchName, No_Of_Copies( (Title=‘The Lost Tribe’ (BOOK)) * CaB) BookId Chapter 5-50 Problem 6.18 in 6th edition c. Retrieve the names of all borrowers who do not have any books checked out CSE 4701 SELECT Name FROM BORROWER B WHERE NOT EXIST ( SELECT * FROM BOOK_LOANS L WHERE B.CardNo = L.CardNo ) d. For each book that is loaned out from the Sharpstown branch and whose Due_date is today, retrieve the book title, the borrower’s name, and the borrower’s address. SELECT B.Title, R.Name, R.Address FROM BOOK B, BORROWER R, BOOK_LOANS BL, LIBRARY_BRANCH LB WHERE LB.BranchName='Sharpstown' AND LB.BranchId=BL.BranchId AND BL.DueDate='today' AND BL.CardNo=R.CardNo AND BL.BookId=B.BookId Chapter 5-51 Problem 8.11/6.18 in 6th edtion CSE 4701 e. For each library branch, retrieve the branch name and the total number of books loaned out from that branch. SELECT L.BranchName, COUNT(*) FROM BOOK_COPIES B, LIBRARY_BRANCH L WHERE B.BranchId = L.BranchId GROUP BY L.BranchName f. Retrieve the names, addresses, and number of books checked out for all borrowers who have more than five books checked out. SELECT B.CardNo, B.Name, B.Address, COUNT(*) FROM BORROWER B, BOOK_LOANS L WHERE B.CardNo = L.CardNo GROUP BY B.CardNo HAVING COUNT(*) > 5 g. For each book authored (or coauthored) by Stephen King, retrieve the title and the number of copies owned by the library branch whose name is Central. SELECT TItle, NoOfCopies FROM ( ( (BOOK_AUTHORS NATURAL JOIN BOOK) NATURAL JOIN BOOK_COPIES) NATURAL JOIN LIBRARY_BRANCH) WHERE Author_Name = 'Stephen King' and BranchName = 'Central' Chapter 5-52 Homework 3 from Spr 2015 Problem 4.10 in 6th edition CSE 4701 Chapter 5-53 Problem 4.10 in 6th edition CSE 4701 Chapter 5-54 Problem 4.10 in 6th edition CSE 4701 (a) Retrieve the names of employees in department 5 who work more than 10 hours per week on the 'ProductX' project. SELECT LNAME, FNAME FROM EMPLOYEE, WORKS_ON, PROJECT WHERE DNO=5 AND SSN=ESSN AND PNO=PNUMBER AND PNAME='ProductX' AND HOURS>10 SELECT LNAME, FNAME FROM EMPLOYEE WHERE DNO=5 AND SSN IN ( SELECT ESSN FROM WORKS_ON WHERE HOURS>10 AND PNO IN ( SELECT PNUMBER FROM PROJECT WHERE PNAME='ProductX' ) ) LNAME FNAME Smith John English Joyce Chapter 5-55 Problem 4.10 in 6th edition CSE 4701 (b) List the names of employees who have a dependent with the same first name as themselves. SELECT LNAME, FNAME FROM EMPLOYEE, DEPENDENT WHERE SSN=ESSN AND FNAME=DEPENDENT_NAME Another possible SQL query uses nesting as follows: SELECT LNAME, FNAME FROM EMPLOYEE WHERE EXISTS ( SELECT * FROM DEPENDENT WHERE FNAME=DEPENDENT_NAME AND SSN=ESSN ) Result (empty): Chapter 5-56 Problem 4.10 in 6th edition CSE 4701 (c) Find the names of employees that are directly supervised by 'Franklin Wong'. LNAME FNAME Smith John Narayan Ramesh English Joyce SELECT E.LNAME, E.FNAME FROM EMPLOYEE E, EMPLOYEE S WHERE S.FNAME='Franklin' AND S.LNAME='Wong' AND E.SUPERSSN=S.SSN Another possible SQL query uses nesting as follows: SELECT LNAME, FNAME FROM EMPLOYEE WHERE SUPERSSN IN ( SELECT SSN FROM EMPLOYEE WHERE FNAME='Franklin' AND LNAME='Wong' ) Chapter 5-57 Problem 4.10 in 6th edition CSE 4701 (d) For each project, list the project name and the total hours per week (by all employees) spent on that project. SELECT PNAME, SUM (HOURS) FROM PROJECT, WORKS_ON WHERE PNUMBER=PNO GROUP BY PNAME Result: PNAME SUM(HOURS) ProductX 52.5 ProductY 37.5 ProductZ 50.0 Computerization55.0 Reorganization 25.0 Newbenefits 55.0 Chapter 5-58 Problem 4.10 in 6th edition CSE 4701 (e) Retrieve the names of employees who work on every project. SELECT LNAME, FNAME FROM EMPLOYEE WHERE NOT EXISTS ( SELECT PNUMBER FROM PROJECT WHERE NOT EXISTS ( SELECT * FROM WORKS_ON WHERE PNUMBER=PNO AND ESSN=SSN ) ) Result (empty): Chapter 5-59 Problem 4.10 in 6th edition CSE 4701 (f) Retrieve the names of employees who do not work on any project. SELECT LNAME, FNAME FROM EMPLOYEE WHERE NOT EXISTS ( SELECT * FROM WORKS_ON WHERE ESSN=SSN ) Result (empty): Chapter 5-60 Problem 4.10 in 6th edition CSE 4701 (g) For each department, retrieve the department name, and the average salary of employees working in that department. SELECT DNAME, AVG (SALARY) FROM DEPARTMENT, EMPLOYEE WHERE DNUMBER=DNO GROUP BY DNAME Result: DNAME AVG(SALARY) Research 33250 Administration 31000 Headquarters 55000 Chapter 5-61 Problem 4.10 in 6th edition CSE 4701 (i) Find the names and addresses of employees who work on at least one project located in Houston but whose department has no location in Houston. SELECT LNAME, FNAME, ADDRESS FROM EMPLOYEE WHERE EXISTS ( SELECT * FROM WORKS_ON, PROJECT WHERE SSN=ESSN AND PNO=PNUMBER AND PLOCATION='Houston' ) AND NOT EXISTS ( SELECT * FROM DEPT_LOCATIONS WHERE DNO=DNUMBER AND DLOCATION='Houston' ) Result: LNAME FNAME ADDRESS Wallace Jennifer 291 Berry, Bellaire, TX Chapter 5-62 Problem 4.10 in 6th edition CSE 4701 (j) List the last names of department managers who have no dependents. SELECT LNAME, FNAME FROM EMPLOYEE WHERE EXISTS ( SELECT * FROM DEPARTMENT WHERE SSN=MGRSSN ) AND NOT EXISTS ( SELECT * FROM DEPENDENT WHERE SSN=ESSN ) Result: LNAME FNAME Borg James Chapter 5-63 Homework 4 from Spring 2015 CSE 4701 Problem 3.3 for the Chinook Database Schema a. Find the list of all Customers and Employees that have the same last name and print out the Last Name (only once), Address, City, and State for each. b. Find and print the Customer Names (First and Last) and Company Name of all Customers that have purchased a Rock Album. (where the Name is ‘Rock’ in the Genre table). c. Find all of print album name and tracks of all of the albums by the composer James Hetfield, grouped by Album. d. For each customer that lives in Canada (CA- Country attribute of Customer), find all invoices and for each result, and print Customer Last Name, number of invoices for customer, and the total amount paid for all invoices. Chapter 5-64 Chinook EER CSE 4701 Chapter 5-65 Problems 3.3a and 3.3b CSE 4701 Find the list of all Customers and Employees that have the same last name and print out the Last Name (only once), Address, City, and State for each. SELECT employee.LastName, employee.Address, employee.City, employee.State, customer.Address, customer.city, customer.state FROM chinook.employee, chinook.customer WHERE employee.LastName = customer.LastName; Find and print the Customer Names (First and Last) and Company Name of all Customers that have purchased a Rock Album. (where the Name is ‘Rock’ in the Genre table). SELECT DISTINCT customer.FirstName, customer.LastName, customer.Company FROM chinook.customer, chinook.invoice, chinook.invoiceline, chinook.track, chinook.genre WHERE customer.CustomerId = invoice.CustomerId AND invoice.InvoiceId = invoiceline.InvoiceId AND invoiceline.TrackId = track.TrackId Chapter 5-66 Problems 3.3c and 3.d CSE 4701 Find all of print album name and tracks of all of the albums by the composer James Hetfield, grouped by Album. SELECT album.title, track.name FROM chinook.album, chinook.track WHERE album.AlbumId = track.AlbumId AND track.Composer LIKE '%Hetfield%'; For each customer that lives in Canada (CA- Country attribute of Customer), find all invoices and for each result, and print Customer Last Name, number of invoices for customer, and the total amount paid for all invoices. SELECT customer.LastName, COUNT(invoice.InvoiceId), SUM(invoice.total) FROM chinook.customer, chinook.invoice WHERE customer.Country = 'Canada' AND customer.CustomerId = invoice.CustomerId Chapter 5-67 Homework 4 from Spring 2015 CSE 4701 Problem 3.4 for the Northwind Database Schema a. Find and print the company names and company addresses of all Suppliers that supply the category name Seafood. b. Count and print the number of suppliers for each of the eight different categories of food which by name are: Beverages, Condiments, Confections, Dairy Products, Grains/Cereals, Meat/Poultry, Produce, Seafood. c. For each country (ShipCountry in Orders), total the Freight charges. The countries are: France, Germany, Brazil, Belgium, Switzerland, Venezuela, Austria, Mexico, USA, Sweden, Finland, Italy, Spain, UK, Ireland, Portugal, Canada, Denmark, Poland, Norway, Argentina Chapter 5-68 Northwind Schema CSE 4701 Northwind EER Chapter 5-69 Problem 4.3a CSE 4701 Find and print the company names and company addresses of all Suppliers that supply the category name Seafood. SELECT DISTINCT suppliers.CompanyName, suppliers.Address FROM northwind.suppliers, northwind.categories, northwind.products WHERE suppliers.SupplierID = products.SupplierID AND categories.CategoryID = products.CategoryID AND categories.CategoryName = 'Seafood'; Chapter 5-70 Problem 4.3b CSE 4701 Count and print the number of suppliers for each of the eight different categories of food which by name are: Beverages, Condiments, Confections, Dairy Products, Grains/Cereals, Meat/Poultry, Produce, Seafood. SELECT categories.CategoryName, COUNT(suppliers.SupplierID) FROM northwind.categories, northwind.products, northwind.suppliers WHERE suppliers.SupplierID = products.SupplierID AND products.categoryID = categories.CategoryID GROUP BY categories.CategoryName; Chapter 5-71 Problem 4.3c CSE 4701 For each country (ShipCountry in Orders), total the Freight charges. The countries are: France, Germany, Brazil, Belgium, Switzerland, Venezuela, Austria, Mexico, USA, Sweden, Finland, Italy, Spain, UK, Ireland, Portugal, Canada, Denmark, Poland, Norway, Argentina SELECT orders.ShipCountry, SUM(orders.Freight) FROM northwind.orders GROUP BY orders.ShipCountry; Chapter 5-72 Concluding Remarks CSE 4701 What have we Seen in Chapter 5? Complex Data Manipulation in SQL Nested Queries Grouping and Aggregation Order by and Having Views Sets Tuple Variable Other Complex Queries and Operations Strongly Encouraged to Engage in Practice with your DBMS of Choice for your Project Chapter 5-73