Presentation is loading. Please wait.

Presentation is loading. Please wait.

SQL-II Reading: C&B, Chap 6, 7, 8 & 9. Dept. of Computing Science, University of Aberdeen2 In this lecture you will learn how to sort and group query.

Similar presentations


Presentation on theme: "SQL-II Reading: C&B, Chap 6, 7, 8 & 9. Dept. of Computing Science, University of Aberdeen2 In this lecture you will learn how to sort and group query."— Presentation transcript:

1 SQL-II Reading: C&B, Chap 6, 7, 8 & 9

2 Dept. of Computing Science, University of Aberdeen2 In this lecture you will learn how to sort and group query results how to calculate aggregates and other derived data how to insert, modify & delete row data the role of NULL values in databases how to combine query results using set operations how to compose and use nested SELECT queries

3 Dept. of Computing Science, University of Aberdeen3 More Control Over SELECT What have we achieved so far using SELECT? –Retrieve data from all the rows and columns (whole table) –Retrieve data from all the rows and select columns –Retrieve data from select rows and columns Sometimes we want to re-format the output from SELECT: –E.g. for reports... Examples of additional processing: –Eliminate duplicates –Sort and/or group the results –Rename column headings –Calculate totals, averages, etc. (often called aggregates) –Combine results from different tables

4 Dept. of Computing Science, University of Aberdeen4 Use of DISTINCT List the property numbers of all properties that have been viewed Query1: SELECT propertyNo FROM Viewing; Query2: SELECT DISTINCT propertyNo FROM Viewing; Viewing ClientNoPropertyNoViewDateComment CR56PA1424-May-01too small CR56PG3628-Apr-01 CR56PG426-May-01 CR62PA1414-May-01no dining room CR76PG420-Apr-01too remote Query2 propertyNo PA14 PG36 PG4 Query1 propertyNo PA14 PG36 PG4 PA14 PG4

5 Dept. of Computing Science, University of Aberdeen5 ORDER BY Produce a list of salaries for all staff, arranged in descending order of salary Query1: SELECT staffNo, fName, lName, salary FROM Staff ORDER BY salary DESC; Query2: SELECT staffNo, fName, lName, salary FROM Staff ORDER BY 4 ASC; Staff StaffNoFnameLnamePositionSexDOBSalaryBranchNo SA9MaryHoweAssistantF19-Feb B007 SG14DavidFordSupervisorM24-Mar B003 SG37AnnBeechAssistantF11-Oct B003 SG5SusanBrandManagerF03-Jun B003 SL21JohnWhiteManagerM01-Oct B005 SL41JulieLeeAssistantF13-Jun B005 Query1 staffNofNamelNamesalary SL41JulieLee90000 SL21JohnWhite30000 SG5SusanBrand24000 SG14DavidFord18000 SG37AnnBeech12000 SA9MaryHowe9000 Query2 staffNofNamelNamesalary SA9MaryHowe9000 SG37AnnBeech12000 SG14DavidFord18000 SG5SusanBrand24000 SL21JohnWhite30000 SL41JulieLee90000

6 Dept. of Computing Science, University of Aberdeen6 Calculated Fields Produce a list of monthly salaries for all staff, showing the staff number, the first and last names, and the salalry details Query1 SELECT staffNo, fName, lName, salary/12 FROM Staff; StaffNoFnameLnamePositionSexDOBSalaryBranchNo SA9MaryHoweAssistantF19-Feb B007 SG14DavidFordSupervisorM24-Mar B003 SG37AnnBeechAssistantF11-Oct B003 SG5SusanBrandManagerF03-Jun B003 SL21JohnWhiteManagerM01-Oct B005 SL41JulieLeeAssistantF13-Jun B005 Staff staffNofNamelNameExpr1003 SA9MaryHowe750 SG14DavidFord1500 SG37AnnBeech1000 SG5SusanBrand2000 SL21JohnWhite2500 SL41JulieLee7500 Query1

7 Dept. of Computing Science, University of Aberdeen7 Renaming Columns When new fields are calculated we can name them using AS Query1: SELECT staffNo, fName, lName, salary/12 AS monthlySalary FROM Staff; staffNofNamelNamemonthlySalary SA9MaryHowe750 SG14DavidFord1500 SG37AnnBeech1000 SG5SusanBrand2000 SL21JohnWhite2500 SL41JulieLee7500 StaffNoFnameLnamePositionSexDOBSalaryBranchNo SA9MaryHoweAssistantF19-Feb B007 SG14DavidFordSupervisorM24-Mar B003 SG37AnnBeechAssistantF11-Oct B003 SG5SusanBrandManagerF03-Jun B003 SL21JohnWhiteManagerM01-Oct B005 SL41JulieLeeAssistantF13-Jun B005 Staff Query1

8 Dept. of Computing Science, University of Aberdeen8 SQL Aggregate Functions We do not want to just retrieve data We also want to summarise data Aggregate functions compute summarization (or aggregation) of data Aggregate functions –SUM –AVG –MIN –MAX –COUNT

9 Dept. of Computing Science, University of Aberdeen9 SUM, MIN, MAX, AVG Find the minimum, maximum, average and sum of staff salary Query1 SELECT MIN(salary) AS myMin, MAX(salary) AS myMax,AVG(salary) AS myAvg, SUM(salary) AS mySum FROM Staff; myMinmyMaxmyAvgmySum StaffNoFnameLnamePositionSexDOBSalaryBranchNo SA9MaryHoweAssistantF19-Feb B007 SG14DavidFordSupervisorM24-Mar B003 SG37AnnBeechAssistantF11-Oct B003 SG5SusanBrandManagerF03-Jun B003 SL21JohnWhiteManagerM01-Oct B005 SL41JulieLeeAssistantF13-Jun B005 Staff Query1

10 Dept. of Computing Science, University of Aberdeen10 COUNT(*) Counts the number of rows in a table –Including the rows that have duplicates and nulls SELECT Count(*) as WomenStaff FROM Staff WHERE Sex='F'; SELECT list (target list) cannot refer to any other column. WomenStaff 4 StaffNoFnameLnamePositionSexDOBSalaryBranchNo SA9MaryHoweAssistantF19-Feb B007 SG14DavidFordSupervisorM24-Mar B003 SG37AnnBeechAssistantF11-Oct B003 SG5SusanBrandManagerF03-Jun B003 SL21JohnWhiteManagerM01-Oct B005 SL41JulieLeeAssistantF13-Jun B005 Staff Query1

11 Dept. of Computing Science, University of Aberdeen11 GROUP BY Aggregate functions help us to summarise the whole column(s) of data into one row. Sometimes we want to group data before applying aggregate functions –This gives us subtotals rather than overall total GROUP BY is used to achieve that

12 Dept. of Computing Science, University of Aberdeen12 GROUP BY - Example Find the number of staff working in each branch and the sum of their salaries Query1: SELECT branchNo, Count(staffNo) AS myCount, SUM(salary) AS mySum FROM Staff GROUP BY branchNo; StaffNoFnameLnamePositionSexDOBSalaryBranchNo SA9MaryHoweAssistantF19-Feb B007 SG14DavidFordSupervisorM24-Mar B003 SG37AnnBeechAssistantF11-Oct B003 SG5SusanBrandManagerF03-Jun B003 SL21JohnWhiteManagerM01-Oct B005 SL41JulieLeeAssistantF13-Jun B005 Staff branchNomyCountmySum B B B Query1

13 Dept. of Computing Science, University of Aberdeen13 HAVING Query1: SELECT branchNo, Count(staffNo) AS myCount, SUM(salary) AS mySum FROM Staff GROUP BY branchNo HAVING COUNT(staffNo)>1; branchNomyCountmySum B B StaffNoFnameLnamePositionSexDOBSalaryBranchNo SA9MaryHoweAssistantF19-Feb B007 SG14DavidFordSupervisorM24-Mar B003 SG37AnnBeechAssistantF11-Oct B003 SG5SusanBrandManagerF03-Jun B003 SL21JohnWhiteManagerM01-Oct B005 SL41JulieLeeAssistantF13-Jun B005 Staff Query1

14 Dept. of Computing Science, University of Aberdeen14 Adding Data to a Table using INSERT General format: INSERT INTO TableName (colname1, colname2,...) VALUES (value1, value2,...); Example: INSERT INTO Staff (StaffNo, Salary, Position, Lname) VALUES (322, 15000, 'Assistant', 'Smith'); SELECT * FROM Staff;

15 Dept. of Computing Science, University of Aberdeen15 Why Do DB Systems Allow NULLs ? A NULL value can be used to represent several situations: Don't care; Don't know; Don't know yet; Used to know! SQL has special rules and logic to handle NULLs: SELECT * FROM Staff WHERE Fname IS NULL; NB. WHERE Colname = 'NULL' does not work ! Can also say: WHERE Colname IS NOT NULL NULLs can be useful, difficult, or dangerous Use NULLs wisely!

16 Dept. of Computing Science, University of Aberdeen16 Modifying & Deleting Data Changing specific values in a table: UPDATE Staff SET Salary = 1.05 * Salary WHERE Position = 'Director'; Deleting specific rows: DELETE FROM Staff WHERE Fname IS NULL; Deleting all rows of a table: DELETE FROM Staff; Completely removing a table is a DDL operation: DROP TABLE Staff;

17 Dept. of Computing Science, University of Aberdeen17 Combining Results Tables Sometimes its useful to be able to combine query results using set operations: R S R U S R - S (a) Union(b) Intersection (c) Difference R S S S R R

18 Dept. of Computing Science, University of Aberdeen18 Set Operations in SQL Syntax: (SELECT...) UNION (SELECT...) (SELECT...) INTERSECT (SELECT...) (SELECT...) EXCEPT (SELECT...) Some DBMSs use MINUS instead of EXCEPT For set operations, the tables must be union- compatible –i.e. have the same number and types of columns

19 Dept. of Computing Science, University of Aberdeen19 Set Operation Example List the cities with both a branch office & a property for rent: (SELECT City FROM Branch) INTERSECT (SELECT City FROM PropertyForRent); Cities with branch office OR a property for rent: UNION Cities with branch office but NO props for rent: EXCEPT

20 Dept. of Computing Science, University of Aberdeen20 Using Subqueries - Nested SELECTs If we know that a SELECT statement will produce a single value, we can use this value directly in a simple predicate. Example: find all members of staff who earn more than Smith: SELECT * FROM Staff WHERE Salary > (SELECT Salary FROM Staff WHERE Lname ='Smith');

21 Dept. of Computing Science, University of Aberdeen21 Subqueries That Give a List of Values If the SELECT statement is expected to produce a list of values, we can use the IN, ANY, ALL or EXISTS keywords to operate on the list. Example: find those members of staff who are not managers but earn more than at least one manager: SELECT * FROM Staff WHERE Position <> 'Manager' AND Salary > ANY (SELECT Salary FROM Staff WHERE Position = 'Manager'); ALL: Predicate is true if test is true for all list elements IN: Predicate is true if the test element is in the list EXISTS: Predicate is true if list is non-empty

22 Dept. of Computing Science, University of Aberdeen22 Summary So Far... SQL is a powerful but quirky" query language SQL is not like other programming languages (no variables) You can answer many kinds of question... You can build up complex queries from simpler sub- queries It often requires thought to compose complex queries... Approach: Break problem into sub-parts, and then build up final query... Next lecture: queries using multiple tables (joins)


Download ppt "SQL-II Reading: C&B, Chap 6, 7, 8 & 9. Dept. of Computing Science, University of Aberdeen2 In this lecture you will learn how to sort and group query."

Similar presentations


Ads by Google