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 [email protected] 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 (prior slide) Chapter 5-4 How Does Nested Query Work? CSE 4701 Nested Query Selects DNUMBER of 'Research' Dept. 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 Set of DNUMBER (SELECT DNUMBER D1, D2, etc. FROM DEPARTMENT WHERE Dname=’Research' ) Chapter 5-5 Nested Query Operates on Department Table CSE 4701 SELECT FNAME, LNAME, ADDRESS FROM EMPLOYEE WHERE DNO IN (SELECT DNUMBER FROM DEPARTMENT WHERE Dname=’Research' ) What Does the Nested Query Return? Set with one Result: 5 Chapter 5-6 What Does Outer Query Do? CSE 4701 SELECT FNAME, LNAME, ADDRESS FROM EMPLOYEE WHERE DNO IN (SELECT DNUMBER DNO IN: FROM DEPARTMENT 5 WHERE Dname=’Research' ) DNO is IN Set of Values Returned by Inner Query What Does the Outer Query Return? All Employees where DNO = 5 Chapter 5-7 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-8 How Does it Work? CSE 4701 SELECT FROM WHERE (SELECT FROM WHERE E.FNAME, E.LNAME Inner Query Returns EMPLOYEE AS E Relation a set of E.SSN IN ESSNs for All Emps ESSN that have Dependents DEPENDENT with the same FNAME ESSN=E.SSN AND E.FNAME=DEPENDENT_NAME) Set with two Result: 123456789 333445555 Alice Franklin Joy Abner John Alice Elizabeth Chapter 5-9 What Does Outer Query Do? CSE 4701 SELECT FROM WHERE (SELECT FROM WHERE E.FNAME, E.LNAME Returns the Employee EMPLOYEE AS E Names for all elements E.SSN IN In the set: ESSN 123456789 DEPENDENT 333445555 ESSN=E.SSN AND E.FNAME=DEPENDENT_NAME) Returns FNAME John Franklin LNAME Smith Wong Chapter 5-10 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-11 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-12 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-13 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-14 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-15 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-16 Results of Query 24: CSE 4701 SELECT DNO, COUNT (*), AVG (SALARY) FROM EMPLOYEE GROUP BY DNO Chapter 5-17 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-18 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-19 Results of Query 26: After Applying the WHERE/GROUP BY Clauses Two Groups Not Selected Based on Having Constraint CSE 4701 Chapter 5-20 Results of Query 26: After Applying the HAVING Clause Condition CSE 4701 3 3 3 3 Chapter 5-21 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-22 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-23 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-24 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-25 ASC DESC Example CSE 4701 Query 15: Retrieve a list of Employees and the Projects each works in, ordered by Dept in alphabetical order, and within each Dept., alphabetically in reverse 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 ASC DNAME, DESC LNAME Chapter 5-26 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-27 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-28 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-29 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-30 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-31 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-32 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-33 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-34 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 can be Modified Chapter 5-35 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-36 Other SQL Query Examples CSE 4701 Homework 2 Spring 2015 Book Database Employee/Project/Department Database Northwind Chapter 5-37 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-38 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-39 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-40 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-41 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-42 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-43 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-44 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-45 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-46 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-47 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-48 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-49 View Concepts/Examples REM updatable view CSE 4701 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%”; Chapter 5-50 View Concepts/Examples REMcreate row outside view CSE 4701 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-51 Homework 3 from Spr 2015 Problem 4.10 in 6th edition CSE 4701 Chapter 5-52 Problem 4.10 in 6th edition CSE 4701 Chapter 5-53 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 LNAME FNAME SELECT LNAME, FNAME FROM EMPLOYEE Smith John WHERE DNO=5 AND SSN IN English Joyce ( SELECT ESSN FROM WORKS_ON WHERE HOURS>10 AND PNO IN ( SELECT PNUMBER FROM PROJECT WHERE PNAME='ProductX' ) ) Chapter 5-54 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-55 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-56 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-57 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-58 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-59 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-60 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-61 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-62 Other SQL Queries Hmwk 4 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 4-63 Explaining Northwind Schema CSE 4701 Suppliers: A Suppliers Contact Info and web link. Products: Names, suppliers, and Prices Categories: Categories of Northwind products such as Beverages, Condiments, Confections, Dairy Products, Grains/Cereals, Meat/Poultry, Produce, Seafood Orders: For each Customer with dates &Shipping Order Details: Products, quantities, and price. Employees: Typical Info. Customers: Typical Info. Shippers: Typical Info. Chapter 4-64 Northwind Schema CSE 4701 Chapter 4-65 a.Find and print the company names and company addresses of all Suppliers that supply the category name Seafood. CSE 4701 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 4-66 a.Count/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. CSE 4701 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 4-67 For each country (ShipCountry in Orders), total the Freight charges. CSE 4701 SELECT orders.ShipCountry, SUM(orders.Freight) FROM northwind.orders GROUP BY orders.ShipCountry; Chapter 4-68 Other SQL Queries Hmwk 2 Fall 2015 CSE 4701 Find the list of all customers from United Kingdom sorted by Company Name in ascending order and return the company Name and Country. Find the number of customers that are located in each country. Find the Product Name, UnitPrice, and UnitsInStock and Sorted by ProductName for all products where the product name starts with “Ch”. Chapter 4-69 Find list of all customers from United Kingdom CSE 4701 SELECT northwind.suppliers.CompanyName, northwind.suppliers.country FROM northwind.suppliers WHERE northwind.suppliers.Country="UK" ORDER BY northwind.suppliers.CompanyName ASC Exotic Liquids UK Specialty Biscuits, Ltd. UK Chapter 4-70 Find number of customers in each country. CSE 4701 SELECT northwind.customers.country, COUNT(*) FROM northwind.customers WHERE northwind.customers.country IS NOT NULL GROUP BY northwind.customers.country Argentina 3 Austria 2 Belgium 2 Brazil 9 Canada 3 Denmark 2 Finland 2 France 11 Germany 11 Ireland 1 Italy 3 Mexico 5 Norway 1 Poland 1 Portugal 2 Spain 5 Sweden 2 Switzerland 2 UK 7 USA 13 Venezuela 4 Chapter 4-71 Find the Product Name …starts with “Ch”. CSE 4701 SELECT northwind.products.productid, northwind.products.productname, northwind.products.UnitsinStock FROM northwind.products WHERE northwind.products.productname LIKE 'CH%'; 1 Chai 39 2 Chang 17 39 Chartreuse verte 69 4 Chef Anton's Cajun Seasoning 53 5 Chef Anton's Gumbo Mix 0 48 Chocolade 15 Chapter 4-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
© Copyright 2026 Paperzz