Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 More SQL Aggregates, Ordering, Grouping, Subqueries and Data Definition Lecture 6.

Similar presentations


Presentation on theme: "1 More SQL Aggregates, Ordering, Grouping, Subqueries and Data Definition Lecture 6."— Presentation transcript:

1 1 More SQL Aggregates, Ordering, Grouping, Subqueries and Data Definition Lecture 6

2 2 Aggregates SELECT MAX(Fine) as maxfine FROM Loan; Loan Loan#catnoMemnoLoanDate DueDate Fine L0002B0001M000105/10/9704/12/97£62.10 L0003B0002M000105/12/9705/03/98£53.00 L0004B0003M000105/12/9705/03/98£53.00 L0006B0004M000213/12/9713/03/98£52.20 L0008B0000M000216/01/9816/04/98£48.80 L0009B0005M000318/08/9918/11/99£75.00 L0010B0006M000419/08/9920/11/99NULL SELECT Count(*) FROM Loan; maxfine £75.00 £354:10 £ SELECT SUM(Fine) FROM Loan; SELECT AVG(Fine) FROM Loan; SELECT Count(Fine) FROM Loan;

3 3 Ordering SELECT Memno, Fine FROM Loan ORDER BY Memno, Fine; Memno Fine M0001£53.00 M0001£62.10 M0002£48.80 M0002£52.20 M0003£75.00 Memno Fine M0001£62.10 M0001£53.00 M0002£52.20 M0002£48.80 M0003£75.00 SELECT Memno, Fine FROM Loan ORDER BY Memno, Fine DESC;

4 4 Grouping SELECT Memno, COUNT(*) AS num_loans FROM Loan GROUP BY Memno; Loan#Book#Memno L0002B0001M0001 L0003B0002M0001 L0004B0003M0001 L0006B0004M0002 L0008B0000M0002 Memno num_loans M M How many loans does each member have?

5 5 Grouping SELECT memno, SUM(fine) AS total_fine FROM Loan GROUP BY memno ; memno catno fine M0001B0002£53.00 M0001B0003£53.00 M0002B0004£52.20 M0003B0005£75.00 memno total_fine M0001 £ M0002 £52.20 M0003 £75.00 What is the total fine paid by each member?

6 6 Warning about Grouping The Select attributes can only contain the attribute grouped on + aggregate functions memno catno fine M0001B0002£53.00 M0001B0003£53.00 M0002B0004£52.20 M0003B0005£75.00 memno memfine M0001 £ M0002 £52.20 M0003 £75.00 Catno B002, B003 B004 B005 SELECT memno, sum(fine) as memfine, catno FROM Loans GROUP BY memno

7 7 Condition on the group - Having SELECT memno, sum(fine) as memfine FROM Loans GROUP BY memno HAVING sum(fine) > 100 ; memno catno fine M0001B0002£53.00 M0001B0003£53.00 M0002B0004£52.20 M0003B0005£75.00 memno memfine M0001 £ What is the total fine paid by each member? Only display members with total fine > £100.

8 8 Subqueries

9 9 Books catnotitleauthorpublishercategory C100Physics HandbookJonesWileyPhysics C200Simply the BestAdvacaatRangersFootball C300Database DesignWilsonMcCallComputing C400Business SocietyNealWileyBusiness C500The MetroAbbeyWileyLeisure C600GraphicsSedgeMaxwellComputing C700Cell BiologyNortonWestBiology Members memnonameaddressage M100FredAberdeen22 M150ColinStirling31 M200DaveDundee21 M250BettyAberdeen67 M300JeanDundee17 Loans catnomemnoborroweddate_retfine C100M10012/09/0120/09/01NULL C300M10001/09/01NULLNULL C400M20004/06/0116/09/01£16.30 C500M20004/08/0116/09/01£16.30 C600M25002/10/0124/10/01£30.00 C700M30010/09/0119/10/01NULL Consider the following tables from which we will do subqueries:

10 10 Subqueries catno title author publisher category catno memno borrowed date_ret fine memno name address age C100 Physics Handbook Jones Wiley Physics C100 M100 12/09/01 20/09/01 NULL M100 Fred Aberdeen 22 C300 Database Design Wilson McCall Computing C300 M100 01/09/01 NULL NULL M100 Fred Aberdeen 22 C400 Business Society Neal Wiley Business C400 M200 04/06/01 16/09/01 £16.30 M200 Dave Dundee 21 C500 The Metro Abbey Wiley Leisure C500 M200 04/08/01 16/09/01 £16.30 M200 Dave Dundee 21 C600 Graphics Sedge Maxwell Computing C600 M250 02/10/01 24/10/01 £30.00 M250 Betty Aberdeen 67 C700 Cell Biology Norton West Biology C700 M300 10/09/01 19/10/01 NULL M300 Jean Dundee 17 Lets say you wanted the names of all members who have borrowed a business or a computing book - a possible query is as follows: SELECT name FROMBooks, Members, Loans WHERE Books.catno = Loans.catno AND Members.memno = Loans.memno AND category IN (Business, Computing); The problem here is that the join in the query (i.e Book.catno = Loan.catno AND Member.memno = Loan.memno) creates the intermediate table as shown below: With more loans the above table can become huge - this is inefficient - better to use subqueries

11 11 Subqueries Subqueries are SELECT statements embedded within another SELECT statement –the results of the inner SELECT statement (or subselect) are used in the outer statement to help determine the contents of the final result inner to outer means evaluating statements from right to left a subselect can be used in the WHERE and HAVING clauses of an outer SELECT statement

12 12 Subqueries Subqueries can be used with a number of operators: –Relational operators (=,, =, ) –IN, NOT IN –ALL –SOME, ANY –EXISTS, NOT EXISTS

13 13 Relational and Aggregate Operators Relational Operators (=,, =, <>) can only be used if the result of the subquery returns a single value i.e subquery must be a scalar subquery. What is the name of the oldest Member SELECT name FROM Members WHERE age = (SELECT MAX(age) FROM Members); SELECT name FROM Members WHERE age = 67; Which equates to: SELECT MAX(age) FROM Members; Scalar subquery returns 67 In general, relational operators are used in conjunction with aggregate operators i.e sum, avg, count, max, min EXAMPLE

14 14 IN and NOT IN Operators Let us again say you wanted the names of all members who have borrowed a business or a computing book - a possible solution using subqueries and the IN operator SELECT name FROM Members WHERE memno IN (SELECT memno FROM Loans WHERE catno IN (SELECT catno FROM Books WHERE category IN (Business, Computing))); Works backwards i.e from inner to outer statements

15 15 IN and NOT IN Operators SELECT catno FROM Book WHERE category IN (Business, Computing); SELECT name FROM Members WHERE memno IN {M100, M200, M250}; SELECT memno FROM Loan WHERE catno IN {C300, C400, C600}; Table subquery returns {C300,C400,C600} Table subquery returns {M100, M200, M250} The previous query works as follows:

16 16 ALL Operator The ALL operator may be used with subqueries that produce a single column of numbers. If the subquery is preceded by the keyword ALL, the condition will only be TRUE if it is satisfied by all the values produced by the subquery EXAMPLE What is the name of the oldest member SELECT name FROM Member WHERE age >= ALL (SELECT age FROM Member); SELECT name FROM Member WHERE age >= ALL {22, 31, 21, 67, 17}; SELECT age FROM Member; look for the rows in Members whose age is greater than or equal to all the values in list

17 17 Example Staff (staffNo, staffName, salary, branchNo*) Branch (branchNo, branchAddress) What does this query do? Select staffName, salary From Staff Where salary > ALL (Select salary From Staff Where branchNo = B003); List all staff whose salary is larger than the salary of every member of staff at branch B003.

18 18 SOME/ANY Operator The SOME operator may be used with subqueries that produce a single column of numbers. SOME and ANY can be used interchangeably. If the subquery is preceded by the keyword SOME, the condition will only be TRUE if it is satisfied by any (one or more) values produced by the subquery EXAMPLE List the names of members who have borrowed books (i.e., members who appear in the Loan table) SELECT name FROM Member WHERE memno = ANY (SELECT DISTINCT memno FROM Loans); SELECT name FROM Member WHERE memno = ANY (M100, M200, M250, M300); SELECT DISTINCT memno FROM Loans

19 19 Example Staff (staffNo, staffName, salary, branchNo*) Branch (branchNo, branchAddress) What does this query do? Select staffName, salary From Staff Where salary > ANY (Select salary From Staff Where branchNo = B003); List all staff whose salary is larger than the salary of at least one member of staff at branch B003.

20 20 EXISTS and NOT EXISTS Operators - Correlated Queries EXISTS and NOT EXISTS produce a simple TRUE/FALSE result. EXISTS is TRUE if and only if there exists at least one row in the result table returned by the subquery; it is FALSE if the subquery returns an empty result table. NOT EXISTS is the opposite of EXISTS EXAMPLE List the titles that have been borrowed by members SELECT title FROM Book B WHERE EXISTS (SELECT * FROM Loan L WHERE L.catno = B.catno); The outer query iterates through all the books, testing if each book appears in the Loan table

21 21 Features of correlated queries A table in the outer query is referenced in the WHERE field of the inner query. The query runs by iterating though the records of the outer FROM table. The inner query is evaluated once for each record, and passes the result back to the outer query.

22 22 Some questions can be answered using joins or queries SELECT Member.name FROM Book, Member, Loan WHERE Book.catno =Loan.catno AND Member.memno=Loan.memno AND Book.category IN ("History", "Computing") ; memno memno catnocatno MemberLoanBook List names of members who have borrowed books on History or Computing SELECT name FROM Member WHERE memno IN (SELECT memno FROM Loan WHERE catno IN (SELECT catno FROM Book WHERE category IN (History, Computing)));

23 23 Equivalent ways of using Subqueries SELECT memno, fine FROM Loan WHERE fine <= ALL (SELECT fine FROM Loan); SELECT memno, fine FROM Loan WHERE fine = (SELECT Min(fine) FROM Loan); memno catno fine M0001B0002£53.00 M0002B0004£52.00 M0003B0005£75.00 M0004 B0007 £26.00 Which member paid the smallest fine?

24 24 Exercise (May 2004 Exam) Employee(empid, name) Project(projid, name) WorkLoad(empid*, projid*, duration) List the number of projects that each employee (empid) is working on. List, in descending order, employee names that are working on the project called Databases. List the employee (empid) who spent the longest duration working on a project. List the employees (name) who have not worked on any project.

25 25 Solution Select empid, count(projid) From WorkLoad Group by empid; Select E.name From Employee E, Project P, WorkLoad L Where E.empid=L.empid AND L.projid=P.projid AND P.name=Databases Order By E.name Desc; Select empid From WorkLoad Where duration = (Select Max(duration) From WorkLoad); Select name From Employee E Where Not Exists(Select * From WorkLoad L Where E.empid = L.empid);

26 26 SQL (Data Definition)

27 27 SQL Data Types Data TypeDeclarations BooleanBOOLEAN CharacterCHARVARCHAR Exact NumericNUMERICDECIMALINTEGER... Approx. NumericFLOATREAL… Date/TimeDATETIME…

28 28 Creating Domains and Tables CREATE TABLE Dept ( deptcode CHAR(3), deptname CHAR(12) ); CREATE TABLE Driver ( first_name CHAR(12), second_nameCHAR(12), ageINTEGER(2) ); CREATE DOMAIN name AS CHAR(12); name name,

29 29 Creating Domains and Tables CREATE TABLE Student ( identitystudent_id, extension integer(4) UNIQUE, student_namenameNOT NULL); CREATE DOMAIN student_id AS CHAR(5) CHECK (VALUE LIKE S%); CREATE DOMAIN student_id AS CHAR (5) CHECK (VALUE LIKE S_ _ _ _); S followed by any number of characters S followed by exactly four characters Attribute name Attribute domain Constraint

30 30 Constraints in tables CREATE TABLE Dept ( deptcode CHAR(3) CONSTRAINT dep_con1 PRIMARY KEY, deptname CHAR(12) ); CREATE TABLE Dept ( deptcode CHAR(3), deptname CHAR(12), CONSTRAINT dep_con1 PRIMARY KEY (deptcode) ); CREATE TABLE Loan ( bookcode CHAR(5), memname CHAR(15), constraint dep_con1 PRIMARY KEY (bookcode, memcode) ); Composite primary key must be entered as table constraint, i.e., separately from the attributes Name of the constraint

31 31 More Constraints in tables CREATE TABLE Staff ( Staffcode CHAR(4), StaffTitleCHAR(3) CONSTRAINT s1_con CHECK (StaffTitle IN (Mr, Ms, Dr)) ); CREATE TABLE Staff ( Staffcode CHAR(4), StaffTitleCHAR(3), CONSTRAINT s1_con CHECK (StaffTitle IN (Mr, Ms, Dr)) );

32 32 Foreign Keys CREATE TABLE Staff ( Staffcode CHAR(4), StaffTitleCHAR(3), DeptCHAR(4) REFERENCES Department(Deptcode) ); CREATE TABLE Department ( Deptcode CHAR(4), DeptnameCHAR(3), CONSTRAINT dep_con1 PRIMARY KEY (Deptcode) ); CREATE TABLE Staff ( Staffcode CHAR(4), StaffTitleCHAR(3), DeptCHAR(4), FOREIGN KEY (Dept) REFERENCES Department ); Optional, if its the primary key Can be multiple valued, to match composite primary key

33 33 Link Properties: On Delete, On Update DID Name D1 Art D2 Computing Dept SID Name S1 Fred S2 Bill S3 Jim Staff DID* D1 D2 On delete: Cascade NULL On delete: Set Default On delete: Set Null Link properties

34 34 DID Name D1 Art D2 Computing Dept SID Name S1 Fred S2 Bill S3 Jim Staff DID* D1 D2 On update: Cascade NULL On delete: Set Default On update: Set Null D42 D42 D79 Link properties Link Properties: On Delete, On Update

35 35 Setting link properties in SQL CREATE TABLE Department ( Deptcode CHARACTER(4), DeptnameCHARACTER(3), CONSTRAINT dep_con1 PRIMARY KEY (Deptcode) ); CREATE TABLE Staff ( Staffcode CHARACTER(4), StaffTitleCHARACTER(3), FOREIGN KEY (Dept) REFERENCES Department ON DELETE SET NULL ON UPDATE SET NULL );

36 36 Modifying tables. You can –Add a column –Add/Delete rows –Add/Drop constraints This is not part of the syllabus, but you can refer to Lab 3 for more details…


Download ppt "1 More SQL Aggregates, Ordering, Grouping, Subqueries and Data Definition Lecture 6."

Similar presentations


Ads by Google