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.

Slides:



Advertisements
Similar presentations
SQL -I Reading: C&B, Chaps 6, 7, 8 & 9. Dept. of Computing Science, University of Aberdeen2 In this lecture you will learn The basic concepts and principles.
Advertisements

Dept. of Computing Science, University of Aberdeen1 Writing SELECT SQL Queries Nigel Beacham based on materials.
Transaction Management Reading: CB, Ch. 22. Dept of Computing Science, University of Aberdeen2 In this lecture you will learn the problems of concurrency.
Logical Database Design Reading: C&B, Chap 17. Dept. of Computer Science, University of Aberdeen2 In this lecture you will learn What is logical database.
Relational Model Reading: C&B, Chap 2, 3 & 4. Dept. of Computing Science, University of Aberdeen 2 In this lecture you will learn The concept of Model.
Access Control & Views Reading: C&B, Chap 7. Dept of Computing Science, University of Aberdeen2 In this lecture you will learn the principles of object.
SQL - III Reading: C&B, Chap 6, 7, 8 & 9. Dept. of Computing Science, University of Aberdeen 2 In this lecture you will learn the concept of joining tables.
Database Design: ER Modelling
Query Processing Reading: CB, Chaps 5 & 23. Dept of Computing Science, University of Aberdeen2 In this lecture you will learn the basic concepts of Query.
Data Definition and Integrity Constraints
File Organization & Indexing Reading: C&B, Ch 18 & 23.
SQL. More than 100 DBMS support SQL –Used by DBAs and application programmers –Structured Query Language or SEQUEL –ORACLE-> relation database based on.
Relational Algebra and Relational Calculus
CSC271 Database Systems Lecture # 11.
CSC271 Database Systems Lecture # 13. Summary: Previous Lecture  Grouping through GROUP BY clause  Restricted groupings  Subqueries  Multi-Table queries.
1 Minggu 4, Pertemuan 8 SQL: Data Manipulation (Cont.) Matakuliah: T0206-Sistem Basisdata Tahun: 2005 Versi: 1.0/0.0.
Chapter 6 SQL: Data Manipulation. 2 Objectives of SQL u Database language should allow user to: –create database and relation structures –perform insertion,
Chapter 6 SQL: Data Manipulation Cont’d. 2 ANY and ALL u ANY and ALL used with subqueries that produce single column of numbers u ALL –Condition only.
Agenda TMA01 M876 Block 3 – Using SQL Structured Query Language - SQL A non-procedural language to –Create database and relation structures. –Perform.
Data Manipulation Using MySQL tMyn1 Data Manipulation Using MySQL Ideally, a database language should allow a user to: –Create the database and relation.
SQL: Overview SQL Overview © Pearson Education Limited 1995, 2005.
CSC271 Database Systems Lecture # 12. Summary: Previous Lecture  Row selection using WHERE clause  WHERE clause and search conditions  Sorting results.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
Chapter 6 SQL: Data Manipulation (Advanced Commands) Pearson Education © 2009.
SQL Data Manipulation II Chapter 5 CIS 458 Sungchul Hong.
Chapter 5 SQL: Data Manipulation © Pearson Education Limited 1995, 2005.
Bayu Adhi Tama, ST., MTI. Introduction Relational algebra and relational calculus are formal languages associated with the relational.
Advanced Database Systems
SQL: Data Manipulation I Chapter 5 CIS 458 Sungchul Hong.
1 Pertemuan > > Matakuliah: >/ > Tahun: > Versi: >
Database Management COP4540, SCS, FIU Structured Query Language (Chapter 8)
Chapter 7 SQL: Data Manipulation Chapter #6 in the textbook Pearson Education © 2009.
Chapter 5 Relational Algebra and Relational Calculus Pearson Education © 2009.
Structured Query Language Introduction. Basic Select SELECT lname, fname, phone FROM employees; Employees Table LNAMEFNAMEPHONE JonesMark SmithSara
IST 210 SQL Todd Bacastow IST 210: Organization of Data.
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
Chapter 5 Relational Algebra Pearson Education © 2014.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
CSC271 Database Systems Lecture # 8. Summary: Previous Lecture  Relation algebra and operations  Selection (Restriction), projection  Union, set difference,
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
CSC271 Database Systems Lecture # 7. Summary: Previous Lecture  Relational keys  Integrity constraints  Views.
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
IST 210 More SQL Todd Bacastow IST 210: Organization of Data.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
SQL: Additional Notes. 2 Example 5.3 Use of DISTINCT List the property numbers of all properties that have been viewed. SELECT propertyNo FROM Viewing;
Chapter 6 SQL: Data Manipulation Pearson Education © 2009.
Teacher Workshop Database Design Pearson Education © 2014.
Chapter 11 SQL: Data Manipulation
SQL Query Getting to the data ……..
Chapter Name SQL: Data Manipulation
Chapter Name SQL: Data Manipulation
SQL – Data Manipulation
Relational Algebra and Relational Calculus
Introduction to SQL Chapter 3.
Chapter Name SQL: Data Manipulation Chapter #6 in the textbook
SQL-2 Week 9-11.
Chapter Name SQL: Data Manipulation Chapter #6 in the textbook
Chapter Name SQL: Data Manipulation
Chapter Name SQL: Data Manipulation
Chapter Name SQL: Data Manipulation
SQL – Entire Select.
Chapter 4 Summary Query.
SQL – Data Manipulation
Access: SQL Participation Project
Chapter Name SQL: Data Manipulation
The Relational Algebra
Chapter Name SQL: Data Manipulation Transparencies JOINS
Chapter Name SQL: Data Manipulation Transparencies
Chapter Name SQL: Data Manipulation
Presentation transcript:

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 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

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

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

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

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

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

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

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

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

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

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

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

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;

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!

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;

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

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

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

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

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

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)