Download presentation
Presentation is loading. Please wait.
Published byPercival Robbins Modified over 9 years ago
1
Lecture8:Data Manipulation in SQL Advanced SQL queries Ref. Chapter5 Lecture8 1
2
The Process of Database Design Real World Domain Conceptual model (ERD) Relational Data Model Create schema (DDL) Load Data (DML) Lecture8 2
3
Sample Data in Customer Table custNocustNamecustStcustCityage 1C1Olaya StJeddah20 2C2Mains StRiyadh30 3C3Mains RdRiyadh25 4C4Mains RdDammam 5C5Mains RdRiyadh Lecture8 3
4
Sample Data in Product Table prodNoprodNameprodDesprice 100P0Food100 101P1healthy food100 102P2200 103P3self_raising flour,80%wheat 300 104P4network 80x300 Lecture8 4
5
Sample Data in Orders Table ordNoordDatecustNoprodNoquantity 101-jan-200311002 202-jan-200311011 301-jan-200321021 401-jan-200331002 503-jan-200311011 606-mar-2003210010 Lecture8 5
6
DEPARTMENT EMPLOYEE Lecture8 6
7
O_IdOrderDateOrderPriceCustomer 12008/11/121000Nora 22008/10/231600Sara 32008/09/02700Nora 42008/09/03300Nora 52008/08/302000Yara 62008/10/04100Sara Table orders ( Example 3) Lecture8 7
8
JOIN Often two or more tables are needed at the same time to find all required data These tables must be "joined" together The formal JOIN basically, it computes a new table from those to be joined, the new table contains data in the matching rows of the individual tables. Lecture8 8
9
Types of JOIN Different SQL JOINs types of JOIN:. JOIN: Return rows when there is at least one match in both tables ( INNER JOIN is the same as JOIN) LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table Full Outer Joins : retains rows that area unmatched in both the tables. NOTE: In all the above outer joins, the displayed unmatched columns are filled with NULLS. Lecture8 9
10
Types of JOIN Lecture8 10
11
SQL Examples of Joins ( 1) Simple Join SELECT E.firstName, E.lastName, D.deptName FROM EMPLOYEE E, DEPARTMENT D WHERE E.deptNumber = D.deptNumber; Lecture8 11
12
E.FirstnameE.lastnameD.deptName MandySmithComputer Science DanielHodgesInformation Science ShaskiaRamanthanInformation Science GrahamBurkeComputer Science AnnieNguyenComputer Science This is the result from the matching This is the final result: Lecture8 12
13
SQL Examples of Joins ( 2 ) Joining more than two tables SELECT E.firstName, E.lastName, P.projTitle FROM EMPLOYEE E, WORKS_ON W, PROJECT P WHERE E.employeeNo = W.employeeNo AND W.projNo = P.projNo ; EMPLOYEE WORKS_ON PROJECT E.FirstnameE.lastnameP.projtitle MandySmithProject A DanielHodgesProject A ShaskiaRamanthanProject B GrahamBurkeProject C AnnieNguyenProject A Lecture8 13
14
SQL Examples of Joins ( 3 ) List customers (by customer number, name and address) who have ordered the product 100. SELECT c.custNo, custName, custSt, custCity FROM customer c, orders o WHERE c.custNo=o.custNo AND prodNo=100; custN o custNa me custStcustCityage 1C1Olaya StJeddah20 2C2Mains StRiyadh30 3C3Mains RdRiyadh25 4C4Mains RdDammam 5C5Mains RdRiyadh ordNoordDatecustNoprodNoquantity 101-jan-200311002 202-jan-200311011 301-jan-200321021 401-jan-200331002 503-jan-200311011 606-mar-2003210010 Lecture8 14
15
SQL Examples of Joins ( 4 ) Find the total price of the products ordered by customer 1. SELECT sum(price*quantity) FROM orders, product WHERE orders.prodNo = product.prodNo AND custNo = 1; prodNoprod Name prodDesprice 100P0Food100 101P1healthy food100 102P2200 103P3self_raising flour,80%whea t 300 104P4network 80x300 ordNoordDatecustNoprodNoquantity 101-jan-200311002 202-jan-200311011 301-jan-200321021 401-jan-200331002 503-jan-200311011 606-mar-2003210010 sum(price*quantity) 400 Lecture8 15
16
Outer Joins in Oracle SQL Put an (+) on the potentially deficient side, ie the side where nulls may be added The (+) operator is placed in the join condition next to the table that is allowed to have NULL values. Example (Left Outer Join) : List all customers, and the products ordered if they have ordered some products. SELECT c.custNo, o.prodNo, quantity FROM customer c, orders o WHERE c.custNo = o.custNo (+); Note: a table may be outer joined with only one other table. Which table column to use is important, eg, in above example, do not use o.custNo in place of c.custNo in the SELECT list. Lecture8 16
17
1) Inner Join SQL Example SELECT Student_Name, Advisor_Name FROM Students, Advisors WHERE Students.Advisor_ID= Advisors.Advisor_ID; Lecture8 17
18
2) Left Outer Join SQL Example SELECT Student_Name, Advisor_Name FROM Students, Advisors WHERE Students.Advisor_ID= Advisors.Advisor_ID (+); Lecture8 18
19
3) Right Outer Join SQL Example SELECT Student_Name, Advisor_Name FROM Students, Advisors WHERE Students.Advisor_ID(+)= Advisors.Advisor_ID ; Student_NameAdvisor_Name Student_1advisor 1 Student_5advisor 3 Student_7advisor 3 Student_9advisor 1 Student_10advisor 3 nullAdvisor 5 Lecture8 19
20
4) Full Outer Join SQL Example SELECT Student_Name, Advisor_Name FROM Students, Advisors WHERE Students.Advisor_ID (+) = Advisors.Advisor_ID (+) ; Lecture8 20
21
Lecture8 21
22
Nested Queries (1) Query results are tables, which can also be queried. SELECT * FROM (SELECT prodNo, sum(quantity) AS sum FROM orders GROUP BY prodNo); WHERE sum>10; Equivalent to SELECT prodNo, sum(quantity) as sum FROM orders GROUP BY prodNo HAVING sum(quantity)>10; The inner query is referred to as a subquery prodNosum 10014 1012 1021 prodNosum 10014 Lecture8 22
23
Nested Queries (2) If the query result is a single value, it can be treated as a value, and be compared with other values. Example: Find products with price more than average SELECT prodNo, price FROM product WHERE price > (SELECT AVG(price) FROM product); AVG(price) 200 prodNoprice 103300 104300 Lecture8 23
24
Subquery Subquery with equality: SELECT firstName, lastName FROM EMPLOYEE WHERE deptNumber =(SELECT deptNumber FROM DEPARTMENT WHERE mailNumber = 39); deptNumber D1 firstNamelastName MandySmith GrahamBurke AnnieNguyene Lecture8 24
25
Subquery Subquery with aggregate function: SELECT firstName, lastName, salary FROM EMPLOYEE WHERE salary > (SELECT avg(salary) FROM EMPLOYEE); avg(salary) 51400 firstNamelastNamesalary ShaskiaRaman than58000 AnnieNguyene60000 Lecture8 25
26
Subquery Nested Subquery (use of IN): SELECT firstName, lastName FROM EMPLOYEE WHERE deptNumber IN (SELECT deptNumber FROM DEPARTMENT WHERE location = ‘Bundoora’); deptNumber D1 D3 firstNamelastName MandySmith GrahamBurke AnnieNguyene Lecture8 26
27
Subquery List the products ordered by customers living in Riyadh. SELECT prodNo FROM orders WHERE custNo IN (SELECT custNo FROM customer WHERE custCity =‘Riyadh'); - This query is equivalent to SELECT prodNo FROM orders o, customer c WHERE o.custNo =c.custNo AND custCity = ‘Riyadh'; custNo 2 3 5 prodNo 100 102 Lecture8 27
28
Lecture8 28
29
Queries using EXISTS or NOT EXISTS Queries using EXISTS Designed for use only with subqueries EXISTS return true 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. Syntax SELECT column_name FROM table_name WHERE EXISTS|NOT EXISTS ( subquery ); Lecture8 29
30
Queries using EXISTS or NOT EXISTS Example SELECT firstName, lastName FROM EMPLOYEE E WHERE EXISTS (SELECT * FROM DEPARTMENT D WHERE E.deptNumber = D.deptNumber AND D.location = ‘Bendigo’); firstNamelastName DanielHodges ShaskiaRamanthan Lecture8 30
31
Example. EXISTS Find all customers who have ordered some products. SELECT * FROM customer c WHERE exists (SELECT * FROM orders o WHERE o.custNo =c.custNo); If the subquery is not empty, then the exists condition is true. custNocustNamecustStcustCityage 1C1Olaya StJeddah20 2C2Mains StRiyadh30 3C3Mains RdRiyadh25 4C4Mains RdDammam 5C5Mains RdRiyadh ordNoordDatecustNoprodNoquantity 101-jan-200311002 202-jan-200311011 301-jan-200321021 401-jan-200331002 503-jan-200311011 606-mar-2003210010 Lecture8 31
32
Example. NOT EXISTS Find all customers such that no order made by them has a quantity less than 2. SELECT * FROM customer c WHERE NOT EXISTS (SELECT * FROM orders o WHERE o.custNo = c.custNo AND quantity <2); custNocustNamecustStcustCityage 1C1Olaya StJeddah20 2C2Mains StRiyadh30 3C3Mains RdRiyadh25 4C4Mains RdDammam 5C5Mains RdRiyadh ordNoordDatecustNoprodNoquantity 101-jan-200311002 202-jan-200311011 301-jan-200321021 401-jan-200331002 503-jan-200311011 606-mar-2003210010 custNocustNamecustStcustCityage 3C3Mains RdRiyadh25 Lecture8 32
33
Lecture8 33
34
UNION The UNION operator is used to combine the result-set of two or more SELECT statements. Notice that each SELECT statement within the UNION must 1. have the same number of columns. 2.The columns must also have similar data types. 3. the columns in each SELECT statement must be in the same order. Combines the results of two SELECT statements into one result set, and then eliminates any duplicate rows from that result set. SQL UNION Syntax SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2 Lecture8 34
35
UNION Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL. UNION ALL Combines the results of two SELECT statements into one result set. SQL UNION ALL Syntax SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2 Lecture8 35
36
UNION Example 1 list all the different employees in Norway and USA SELECT E_Name FROM Employees_Norway UNION SELECT E_Name FROM Employees_USA; E_Name Hansen, Ola Svendson, Tove Svendson, Stephen Pettersen, Kari Turner, Sally Kent, Clark Scott, Stephen E_IDE_Name 01Hansen, Ola 02Svendson, Tove 03Svendson, Stephen 04Pettersen, Kari E_IDE_Name 01Turner, Sally 02Kent, Clark 03Svendson, Stephen 04Scott, Stephen "Employees_Norway" “ Employees_USA” Lecture8 36
37
UNION Example 2 SELECT custNo FROM customer WHERE custCity=‘Riyadh' UNION SELECT custNo FROM orders WHERE prodNo=102;// union of the two queries custNocustNam e custStcustCityage 1C1Olaya StJeddah20 2C2Mains StRiyadh30 3C3Mains RdRiyadh25 4C4Mains RdDammam 5C5Mains RdRiyadh ordNoordDatecustNoprodNoquantity 101-jan-200311002 202-jan-200311011 301-jan-200321021 401-jan-200331002 503-jan-200311011 606-mar-2003210010 custNo 2 3 5 Lecture8 37
38
MINUS the MINUS operator returns only unique rows returned by the first query but not by the second. Takes the result set of one SELECT statement, and removes those rows that are also returned by a second SELECT statement. SQL MINUS Syntax SELECT column_name(s) FROM table_name1 MINUS SELECT column_name(s) FROM table_name2 Lecture8 38
39
MINUS Example 1 SELECT prodNo FROM product MINUS SELECT prodNo FROM orders; //difference from the two queries ordNoordDatecustNoprodNoquantity 101-jan-200311002 202-jan-200311011 301-jan-200321021 401-jan-200331002 503-jan-200311011 606-mar-2003210010 prodNoprodNameprodDesprice 100P0Food100 101P1healthy food100 102P2200 103P3self_raising flour,80%wheat 300 104P4network 80x300 ProdNo 103 104 Lecture8 39
40
INTERSECT the INTERSECT operator returns only those rows returned by both queries. Returns only those rows that are returned by each of two SELECT statements. SQL INTERSECT Syntax SELECT column_name(s) FROM table_name1 INTERSECT SELECT column_name(s) FROM table_name2 Lecture8 40
41
INTERSECT SELECT custNo FROM customer WHERE custCity=‘Riyadh' INTERSECT SELECT custNo FROM orders WHERE prodNo=102; // intersect of the two queries custN o custNamecustStcustCityage 1C1Olaya StJeddah20 2C2Mains StRiyadh30 3C3Mains RdRiyadh25 4C4Mains RdDammam 5C5Mains RdRiyadh ordNoordDatecustNoprodNoquantit y 101-jan-200311002 202-jan-200311011 301-jan-200321021 401-jan-200331002 503-jan-200311011 606-mar-2003210010 CustNo 2 Lecture8 41
42
DEPENDENT EMPLOYEE Examples Lecture8 42
43
Examples SELECTemployeeNo, firstName, lastName FROMEMPLOYEE UNION SELECT employeeNo, firstName, lastName FROM DEPENDENT; SELECTemployeeNo FROMEMPLOYEE INTERSECT SELECT employeeNo FROM DEPENDENT Lecture8 43
44
Lecture8 44
45
EMPLOYEE Table Example1 SELECT department_id, count(*), max(salary), min(salary) FROM employee GROUP BY department_id; EMPLOYEE_IDLAST_NAMEFIRST_NAMEJOB_IDMANAGER_IDSALARYCOMMDEPARTMENT_ID 7369SMITHJOHN6677902800NULL20 7499ALLENKEVIN6707698160030030 7505DOYLEJEAN67178392850NULL30 7506DENNISLYNN67178392750NULL30 7507BAKERLESLIE67178392200NULL40 7521WARKCYNTHIA6707698125050030 Lecture8 45
46
EMPLOYEE Table Example2 SELECT Employee_ID, FIRST_NAME,DEPARTMENT_ID FROM employee WHERE salary=(SELECT max(salary) FROM employee); EMPLOYEE_IDLAST_NAMEFIRST_NAMEJOB_IDMANAGER_IDSALARYCOMMDEPARTMENT_ID 7369SMITHJOHN6677902800NULL20 7499ALLENKEVIN6707698160030030 7505DOYLEJEAN67178392850NULL30 7506DENNISLYNN67178392750NULL30 7507BAKERLESLIE67178392200NULL40 7521WARKCYNTHIA6707698125050030 Lecture8 46
47
EMPLOYEE Table Example3 SELECT Employee_ID FROM employee WHERE department_id IN (SELECT department_id FROM department WHERE name=’SALES’); DEPARTMENT Department_IDNameLocation_ID 10ACCOUNTING122 20RESEARCH124 30SALES123 40OPERATIONS167 EMPLOYEE_IDLAST_NAMEFIRST_NAMEJOB_IDMANAGER_IDSALARYCOMMDEPARTMENT_ID 7369SMITHJOHN6677902800NULL20 7499ALLENKEVIN6707698160030030 7505DOYLEJEAN67178392850NULL30 7506DENNISLYNN67178392750NULL30 7507BAKERLESLIE67178392200NULL40 7521WARKCYNTHIA6707698125050030 Lecture8 47
48
EMPLOYEE Table Example4 SELECT name FROM department d WHERE NOT EXISTS (SELECT last_name FROM employee e WHERE d.department_id=e.department_id); DEPARTMENT Department_IDNameLocation_ID 10ACCOUNTING122 20RESEARCH124 30SALES123 40OPERATIONS167 EMPLOYEE_IDLAST_NAMEFIRST_NAMEJOB_IDMANAGER_IDSALARYCOMMDEPARTMENT_ID 7369SMITHJOHN6677902800NULL20 7499ALLENKEVIN6707698160030030 7505DOYLEJEAN67178392850NULL30 7506DENNISLYNN67178392750NULL30 7507BAKERLESLIE67178392200NULL40 7521WARKCYNTHIA6707698125050030 Lecture8 48
49
EMPLOYEE Table Example5 SELECT last_name, d.department_id, d.name FROM employee e, department d WHERE e.department_id (+)= d.department_id AND d.department_id in (SELECT department_id FROM department WHERE name IN (‘RESEARCH’, ’OPERATIONS’)); DEPARTMENT Department_IDNameLocation_ID 10ACCOUNTING122 20RESEARCH124 30SALES123 40OPERATIONS167 EMPLOYEE_IDLAST_NAMEFIRST_NAMEJOB_IDMANAGER_IDSALARYCOMMDEPARTMENT_ID 7369SMITHJOHN6677902800NULL20 7499ALLENKEVIN6707698160030030 7505DOYLEJEAN67178392850NULL30 7506DENNISLYNN67178392750NULL30 7507BAKERLESLIE67178392200NULL40 7521WARKCYNTHIA6707698125050030 Lecture8 49
50
EMPLOYEE Table Example6 SELECT employee_id, First_name, Last_name, Salary FROM employee WHERE last_name like ‘D%’; EMPLOYEE_IDLAST_NAMEFIRST_NAMEJOB_IDMANAGER_IDSALARYCOMMDEPARTMENT_ID 7369SMITHJOHN6677902800NULL20 7499ALLENKEVIN6707698160030030 7505DOYLEJEAN67178392850NULL30 7506DENNISLYNN67178392750NULL30 7507BAKERLESLIE67178392200NULL40 7521WARKCYNTHIA6707698125050030 Lecture8 50
51
Lecture8 51
52
References “Database Systems: A Practical Approach to Design, Implementation and Management.” Thomas Connolly, Carolyn Begg. 5 th Edition, Addison-Wesley, 2009. Lecture8 52
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.