Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5 6e & 8 5e: Complex SQL

Similar presentations


Presentation on theme: "Chapter 5 6e & 8 5e: Complex SQL"— Presentation transcript:

1 Chapter 5 6e & 8 5e: Complex SQL
Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut 191 Auditorium Road, Box U-155 Storrs, CT (860) 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.

2 Variety of Complex SQL Queries
Nested Queries Grouping and Aggregation Order by and Having Views Sets Tuple Variable Other Complex Queries and Operations

3 Recall Earlier Query 1 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?

4 Nested Queries 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)

5 How Does Nested Query Work?
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 WHERE DNO IN (SELECT DNUMBER FROM DEPARTMENT WHERE Dname=’Research' ) Inner Query Returns Set of DNUMBER D1, D2, etc.

6 Nested Query Operates on Department Table
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

7 What Does Outer Query Do?
SELECT FNAME, LNAME, ADDRESS FROM EMPLOYEE WHERE DNO IN (SELECT DNUMBER FROM DEPARTMENT WHERE Dname=’Research' ) DNO is IN Set of Values Returned by Inner Query What Does the Outer Query Return? All Employees where DNO = 5 DNO IN: 5

8 Correlated Nested Queries
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 FROM EMPLOYEE AS E WHERE E.SSN IN (SELECT ESSN FROM DEPENDENT WHERE ESSN=E.SSN AND E.FNAME=DEPENDENT_NAME) Note: This Differs Slightly from 16 in book. Inner Query Returns Relation a set of ESSNs for All Emps that have Dependents with the same FNAME

9 How Does it Work? 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) Inner Query Returns Relation a set of ESSNs for All Emps that have Dependents with the same FNAME Alice Franklin Joy Abner John Elizabeth Set with two Result:

10 What Does Outer Query Do?
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) Returns the Employee Names for all elements In the set: Returns FNAME LNAME John Smith Franklin Wong

11 Query Equivalence 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

12 EXISTS Nested Queries 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 SELECT FNAME, LNAME FROM EMPLOYEE WHERE EXISTS (SELECT * FROM DEPENDENT WHERE SSN=ESSN AND FNAME=DEPENDENT_NAME) There is a analogous NOT EXISTS Inner Query Returns Is True if there is At least one match. Can there be 2 matches?

13 NULLS in SQL Queries 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

14 Aggregate Functions in SQL Queries
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

15 Grouping in SQL Queries
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

16 Grouping in SQL Queries
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

17 Results of Query 24: SELECT DNO, COUNT (*), AVG (SALARY) FROM EMPLOYEE GROUP BY DNO

18 Joins and Grouping in SQL Queries
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

19 The HAVING Clause in SQL Queries
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

20 Two Groups Not Selected Based on Having Constraint
Results of Query 26: After Applying the WHERE/GROUP BY Clauses Two Groups Not Selected Based on Having Constraint

21 Results of Query 26: After Applying the HAVING Clause Condition 3

22 Substring Comparison in SQL Queries
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

23 Substring Comparison in SQL Queries
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

24 Arithmetic Operations in SQL Queries
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'

25 ORDER BY Clause in SQL Queries
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 DNAME, LNAME, FNAME, PNAME FROM DEPARTMENT, EMPLOYEE, WORKS_ON, PROJECT WHERE DNUMBER=DNO AND SSN=ESSN AND PNO=PNUMBER ORDER BY DNAME, LNAME Default is Ascending - Can be ASC/DESC as we’ll see in a Later Example

26 ASC DESC Example 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 DNAME, LNAME, FNAME, PNAME FROM DEPARTMENT, EMPLOYEE, WORKS_ON, PROJECT WHERE DNUMBER=DNO AND SSN=ESSN AND PNO=PNUMBER ORDER BY ASC DNAME, DESC LNAME

27 SQL Support for Views 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”

28 SQL View Definition 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 Reasons for Views Security Increasing Application-Data Independence CREATE VIEW PQ(P#, SUMQTY) AS SELECT P#, SUM(QTY) FROM SP GROUP BY P#;

29 View Definition in Ongoing Example
First View: Attribute Names are Inherited CREATE VIEW WORKS_ON1 AS SELECT FNAME, LNAME, PNAME, HOURS FROM EMPLOYEE, PROJECT, WORKS_ON WHERE SSN=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 ;

30 Queries on Views 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

31 What is View Update Problem?
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: Try to Change the Total Quantity SUMQTY of P1 in PQ from “30” to “40” Why Does a view Update Problem occur? CREATE VIEW PQ(P#, SUMQTY) AS SELECT P#, SUM(QTY) FROM SP GROUP BY P#; If we want to change the total quantity SUMQTY of a part P1 in PQ from “30” to “40”, a view update problem incurs, because this update over view PQ does not give enough information to enable us to map the view update to the base relations without ambiguity.

32 The Book Example - DDL - Create Tables
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);

33 DDL - Create Tables (continued)
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));

34 DDL - Change Table Structure
Add a Column to a Table: 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

35 Views Basis of APIs 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

36 Views in Medical Domain
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

37 Other SQL Query Examples
Homework 2 Spring 2015 Book Database Employee/Project/Department Database Northwind

38 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 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) WHERE AUTHORS LIKE “%Maier”;

39 Other SQL Search: String Matching
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

40 Other SQL Queries 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 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)

41 Using Tuple Variables 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 = “ ”;

42 Ordering Results 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?

43 Set Operations Find books written by Mary or Lisa
SELECT * FROM BOOK WHERE AUTHORS LIKE “LISA%” UNION WHERE AUTHORS LIKE “MARY%”; UNION, INTERSECT, EXCEPT UNION ALL, INTERSECT ALL, and EXCEPT ALL Preserve Duplicates SELECT * FROM BOOK WHERE AUTHORS LIKE “LISA%” OR AUTHORS LIKE “MARY%”;

44 Built-in Aggregate Functions
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;

45 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%”;

46 Nested Subqueries 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…

47 Set Membership: IN, NOT IN
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 WHERE WEEKDAY NOT IN (“MON”, “TUE”);

48 Set Comparison 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);

49 Delete and Update Cancel all orders by Mary on 2/17/2000
DELETE FROM BOOK WHERE DATE= 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= ;

50 View Concepts/Examples
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%”;

51 View Concepts/Examples
REMcreate row outside view INSERT INTO LOW-PRICE-BOOKS VALUES (“ ”, ”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;

52 Homework 3 from Spr 2015 Problem 4.10 in 6th edition

53 Problem 4.10 in 6th edition

54 Problem 4.10 in 6th edition LNAME FNAME Smith John English Joyce
(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

55 Problem 4.10 in 6th edition (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: FROM EMPLOYEE WHERE EXISTS ( SELECT * FROM DEPENDENT WHERE FNAME=DEPENDENT_NAME AND SSN=ESSN ) Result (empty):

56 Problem 4.10 in 6th edition LNAME FNAME Smith John Narayan Ramesh
English Joyce (c) Find the names of employees that are directly supervised by 'Franklin Wong'. 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 WHERE FNAME='Franklin' AND LNAME='Wong' )

57 Problem 4.10 in 6th edition (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 ProductY ProductZ Computerization55.0 Reorganization 25.0 Newbenefits 55.0

58 Problem 4.10 in 6th edition (e) Retrieve the names of employees who work on every project. SELECT LNAME, FNAME FROM EMPLOYEE WHERE NOT EXISTS ( SELECT PNUMBER FROM PROJECT ( SELECT * FROM WORKS_ON WHERE PNUMBER=PNO AND ESSN=SSN ) ) Result (empty):

59 Problem 4.10 in 6th edition (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):

60 Problem 4.10 in 6th edition (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 Administration 31000 Headquarters

61 Problem 4.10 in 6th edition (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 FROM DEPT_LOCATIONS WHERE DNO=DNUMBER AND DLOCATION='Houston' ) Result: LNAME FNAME ADDRESS Wallace Jennifer 291 Berry, Bellaire, TX

62 Problem 4.10 in 6th edition (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 FROM DEPENDENT WHERE SSN=ESSN ) Result: LNAME FNAME Borg James

63 Other SQL Queries Hmwk 4 Spring 2015
Problem 3.4 for the Northwind Database Schema Find and print the company names and company addresses of all Suppliers that supply the category name Seafood. 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. 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

64 Explaining Northwind Schema
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.

65 Northwind Schema

66 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';

67 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. 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;

68 For each country (ShipCountry in Orders), total the Freight charges.
SELECT orders.ShipCountry, SUM(orders.Freight) FROM northwind.orders GROUP BY orders.ShipCountry;

69 Other SQL Queries Hmwk 2 Fall 2015
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”.

70 Find list of all customers from United Kingdom
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.

71 Find number of customers in each country.
Argentina 3 Austria 2 Belgium Brazil 9 Canada Denmark Finland France 11 Germany Ireland 1 Italy Mexico 5 Norway Poland Portugal Spain Sweden Switzerland UK 7 USA 13 Venezuela 4 SELECT northwind.customers.country, COUNT(*) FROM northwind.customers WHERE northwind.customers.country IS NOT NULL GROUP BY northwind.customers.country

72 Find the Product Name …starts with “Ch”.
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 Chartreuse verte 69 4 Chef Anton's Cajun Seasoning 53 5 Chef Anton's Gumbo Mix 48 Chocolade 15

73 Concluding Remarks 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


Download ppt "Chapter 5 6e & 8 5e: Complex SQL"

Similar presentations


Ads by Google