1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set...

77
1 . Ching, Ph.D. • MIS • California State University, Sacramento Week 6 Week 6 October 3 October 3 SQL: Joins, Set Operations, Aggregation SQL: Joins, Set Operations, Aggregation Functions, Functions, Subqueries ANY/ALL and EXIST/NOT EXIST, Subqueries ANY/ALL and EXIST/NOT EXIST, Table Insert, Delete and Drop Table Insert, Delete and Drop Oracle: Format Models, Oracle: Format Models, Substring, Truncation and Modulus Substring, Truncation and Modulus Functions Functions
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    213
  • download

    0

Transcript of 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set...

Page 1: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

1

R. Ching, Ph.D. • MIS • California State University, Sacramento

Week 6Week 6October 3October 3

• SQL: Joins, Set Operations, Aggregation Functions, SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and EXIST/NOT EXIST,Subqueries ANY/ALL and EXIST/NOT EXIST,

Table Insert, Delete and DropTable Insert, Delete and Drop• Oracle: Format Models, Oracle: Format Models,

Substring, Truncation and Modulus Functions Substring, Truncation and Modulus Functions

Page 2: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

2

R. Ching, Ph.D. • MIS • California State University, Sacramento

Using DISTINCTUsing DISTINCT

SELECT DISTINCT(manfuacturer_code)SELECT DISTINCT(manfuacturer_code)

FROM productsFROM products

Result:Result: The non-duplicated manufacturer_codes will be The non-duplicated manufacturer_codes will be retrieved.retrieved.

Page 3: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

3

R. Ching, Ph.D. • MIS • California State University, Sacramento

select distinct(manufacturer_code) from products;select distinct(manufacturer_code) from products;

MAN MAN --- --- AIW AIW BOS BOS CRV CRV DA DA GMI GMI HVC HVC JBL JBL JVC JVC MIT MIT PAN PAN PIN PIN PIO PIO SAM SAM SHE SHE SON SON TEA TEA TEC TEC THN THN YAM YAM

19 rows selected.19 rows selected.

Page 4: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

4

R. Ching, Ph.D. • MIS • California State University, Sacramento

Equi-JoinEqui-Join

• A resulting relation that contains tuples satisfying the A resulting relation that contains tuples satisfying the predicate ofpredicate of equality equality between two attributes of the same between two attributes of the same domain from the Cartesian product of domain from the Cartesian product of RR and and SS

RR RR.aj .aj SS.bj .bj SSRR RR.aj .aj SS.bj .bj SS

Page 5: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

5

R. Ching, Ph.D. • MIS • California State University, Sacramento

Equi-JoinEqui-Join

SQL> SQL> select product_code, p.manufacturer_code,select product_code, p.manufacturer_code, 2 2 m.manufacturer_codem.manufacturer_code 3 3 from products p, manufacturers mfrom products p, manufacturers m 4 4 where p.manufacturer_code = m.manufacturer_code;where p.manufacturer_code = m.manufacturer_code;

PRODUCT_CO MAN MANPRODUCT_CO MAN MAN---------- --- ------------- --- ---RS1B INF INFRS1B INF INFSM165 INF INFSM165 INF INFCC1M INF INFCC1M INF INF100 BOS BOS100 BOS BOS201-IV BOS BOS201-IV BOS BOSVS-100 BOS BOSVS-100 BOS BOS

6 rows selected.6 rows selected.

RS1B INFRS1B INFSM165 INFSM165 INFCC1M INF CC1M INF 100 BOS100 BOS201-IV BOS201-IV BOSVS-100 BOSVS-100 BOS

RS1B INFRS1B INFSM165 INFSM165 INFCC1M INF CC1M INF 100 BOS100 BOS201-IV BOS201-IV BOSVS-100 BOSVS-100 BOS

ADV AdventADV AdventBOS BoseBOS BoseINF InfinityINF Infinity

ADV AdventADV AdventBOS BoseBOS BoseINF InfinityINF Infinity

ProductsProducts ManufacturersManufacturers

AliasesAliases

Page 6: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

6

R. Ching, Ph.D. • MIS • California State University, Sacramento

Outer Joins in OracleOuter Joins in Oracle

• An outer join returns all rows that satisfy the join condition An outer join returns all rows that satisfy the join condition and those rows from one table for which no rows from the and those rows from one table for which no rows from the other satisfy the join condition. other satisfy the join condition.

– Such rows are not returned by a simple join. Such rows are not returned by a simple join.

– To perform an outer join of tables A and B and return To perform an outer join of tables A and B and return all rows from Aall rows from A, apply the outer join operator , apply the outer join operator (+) to (+) to all columns of Ball columns of B in the join condition. in the join condition.

– For all rows in A that have no matching rows in B, a For all rows in A that have no matching rows in B, a NULL is returned for any select list expressions NULL is returned for any select list expressions containing columns of B. containing columns of B.

Page 7: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

7

R. Ching, Ph.D. • MIS • California State University, Sacramento

Left Outer JoinLeft Outer Join

• All rows on the All rows on the leftleft table (i.e., products) are kept table (i.e., products) are kept

SQL> SQL> select product_code, product_description,select product_code, product_description, 2 2 p.manufacturer_code, m.manufacturer_codep.manufacturer_code, m.manufacturer_code 3 3 from products p, manufacturers mfrom products p, manufacturers m 4 4 where p.manufacturer_code = m.manufacturer_codewhere p.manufacturer_code = m.manufacturer_code(+)(+);;

PRODUCT_CO PRODUCT_DESCRIPTION MAN MANPRODUCT_CO PRODUCT_DESCRIPTION MAN MAN---------- ----------------------------------- --- ------------- ----------------------------------- --- ---100 Compact Speakers BOS BOS100 Compact Speakers BOS BOS201-IV Direct/Reflecting Speakers BOS BOS201-IV Direct/Reflecting Speakers BOS BOSVS-100 Center Channel Mini Speaker BOS BOSVS-100 Center Channel Mini Speaker BOS BOSRS1B 2-way Bookshelf Speakers INF INFRS1B 2-way Bookshelf Speakers INF INFSM165 Bookshelf-sized Speakers INF INFSM165 Bookshelf-sized Speakers INF INFCC1M Center Channel Speaker INF INFCC1M Center Channel Speaker INF INF

6 rows selected.6 rows selected.

Page 8: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

8

R. Ching, Ph.D. • MIS • California State University, Sacramento

Right Outer JoinRight Outer Join

• All rows on the All rows on the right right table (i.e., manufacturers) are kepttable (i.e., manufacturers) are kept

SQL> SQL> select product_code, product_description,select product_code, product_description, 2 2 p.manufacturer_code, m.manufacturer_codep.manufacturer_code, m.manufacturer_code 3 3 from products p, manufacturers mfrom products p, manufacturers m 4 4 where p.manufacturer_codewhere p.manufacturer_code(+)(+) = m.manufacturer_code; = m.manufacturer_code;

PRODUCT_CO PRODUCT_DESCRIPTION MAN MANPRODUCT_CO PRODUCT_DESCRIPTION MAN MAN---------- ----------------------------------- --- ------------- ----------------------------------- --- --- ADVADV100 Compact Speakers BOS BOS100 Compact Speakers BOS BOS201-IV Direct/Reflecting Speakers BOS BOS201-IV Direct/Reflecting Speakers BOS BOSVS-100 Center Channel Mini Speaker BOS BOSVS-100 Center Channel Mini Speaker BOS BOSRS1B 2-way Bookshelf Speakers INF INFRS1B 2-way Bookshelf Speakers INF INFSM165 Bookshelf-sized Speakers INF INFSM165 Bookshelf-sized Speakers INF INFCC1M Center Channel Speaker INF INFCC1M Center Channel Speaker INF INF

7 rows selected.7 rows selected.

Page 9: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

9

R. Ching, Ph.D. • MIS • California State University, Sacramento

Cartesian ProductCartesian Product

SQL> SQL> select * from products, manufacturers;select * from products, manufacturers;

RS1B 2-way Bookshelf Speakers INF 188 PR ADV AdventRS1B 2-way Bookshelf Speakers INF 188 PR ADV AdventSM165 Bookshelf-sized Speakers INF 205 PR ADV AdventSM165 Bookshelf-sized Speakers INF 205 PR ADV AdventCC1M Center Channel Speaker INF 164 EA ADV AdventCC1M Center Channel Speaker INF 164 EA ADV Advent100 Compact Speakers BOS 205 PR ADV Advent100 Compact Speakers BOS 205 PR ADV Advent201-IV Direct/Reflecting Speakers BOS 205 PR ADV Advent201-IV Direct/Reflecting Speakers BOS 205 PR ADV AdventVS-100 Center Channel Mini Speaker BOS 116.96 EA ADV AdventVS-100 Center Channel Mini Speaker BOS 116.96 EA ADV AdventRS1B 2-way Bookshelf Speakers INF 188 PR INF InfinityRS1B 2-way Bookshelf Speakers INF 188 PR INF InfinitySM165 Bookshelf-sized Speakers INF 205 PR INF InfinitySM165 Bookshelf-sized Speakers INF 205 PR INF InfinityCC1M Center Channel Speaker INF 164 EA INF InfinityCC1M Center Channel Speaker INF 164 EA INF Infinity100 Compact Speakers BOS 205 PR INF Infinity100 Compact Speakers BOS 205 PR INF Infinity201-IV Direct/Reflecting Speakers BOS 205 PR INF Infinity201-IV Direct/Reflecting Speakers BOS 205 PR INF InfinityVS-100 Center Channel Mini Speaker BOS 116.96 EA INF InfinityVS-100 Center Channel Mini Speaker BOS 116.96 EA INF InfinityRS1B 2-way Bookshelf Speakers INF 188 PR BOS BoseRS1B 2-way Bookshelf Speakers INF 188 PR BOS BoseSM165 Bookshelf-sized Speakers INF 205 PR BOS BoseSM165 Bookshelf-sized Speakers INF 205 PR BOS BoseCC1M Center Channel Speaker INF 164 EA BOS BoseCC1M Center Channel Speaker INF 164 EA BOS Bose100 Compact Speakers BOS 205 PR BOS Bose100 Compact Speakers BOS 205 PR BOS Bose201-IV Direct/Reflecting Speakers BOS 205 PR BOS Bose201-IV Direct/Reflecting Speakers BOS 205 PR BOS BoseVS-100 Center Channel Mini Speaker BOS 116.96 EA BOS BoseVS-100 Center Channel Mini Speaker BOS 116.96 EA BOS Bose

18 rows selected.18 rows selected.

Page 10: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

10

R. Ching, Ph.D. • MIS • California State University, Sacramento

Cartesian ProductCartesian Product

SQL> select * from products, manufacturers;SQL> select * from products, manufacturers;

RS1BRS1B 2-way Bookshelf Speakers INF 188 PR 2-way Bookshelf Speakers INF 188 PR ADVADV Advent AdventSM165 Bookshelf-sized Speakers INF 205 PR ADV AdventSM165 Bookshelf-sized Speakers INF 205 PR ADV AdventCC1M Center Channel Speaker INF 164 EA ADV AdventCC1M Center Channel Speaker INF 164 EA ADV Advent100 Compact Speakers BOS 205 PR ADV Advent100 Compact Speakers BOS 205 PR ADV Advent201-IV Direct/Reflecting Speakers BOS 205 PR ADV Advent201-IV Direct/Reflecting Speakers BOS 205 PR ADV AdventVS-100 Center Channel Mini Speaker BOS 116.96 EA ADV AdventVS-100 Center Channel Mini Speaker BOS 116.96 EA ADV AdventRS1BRS1B 2-way Bookshelf Speakers INF 188 PR 2-way Bookshelf Speakers INF 188 PR INFINF Infinity InfinitySM165 Bookshelf-sized Speakers INF 205 PR INF InfinitySM165 Bookshelf-sized Speakers INF 205 PR INF InfinityCC1M Center Channel Speaker INF 164 EA INF InfinityCC1M Center Channel Speaker INF 164 EA INF Infinity100 Compact Speakers BOS 205 PR INF Infinity100 Compact Speakers BOS 205 PR INF Infinity201-IV Direct/Reflecting Speakers BOS 205 PR INF Infinity201-IV Direct/Reflecting Speakers BOS 205 PR INF InfinityVS-100 Center Channel Mini Speaker BOS 116.96 EA INF InfinityVS-100 Center Channel Mini Speaker BOS 116.96 EA INF InfinityRS1BRS1B 2-way Bookshelf Speakers INF 188 PR 2-way Bookshelf Speakers INF 188 PR BOSBOS Bose BoseSM165 Bookshelf-sized Speakers INF 205 PR BOS BoseSM165 Bookshelf-sized Speakers INF 205 PR BOS BoseCC1M Center Channel Speaker INF 164 EA BOS BoseCC1M Center Channel Speaker INF 164 EA BOS Bose100 Compact Speakers BOS 205 PR BOS Bose100 Compact Speakers BOS 205 PR BOS Bose201-IV Direct/Reflecting Speakers BOS 205 PR BOS Bose201-IV Direct/Reflecting Speakers BOS 205 PR BOS BoseVS-100 Center Channel Mini Speaker BOS 116.96 EA BOS BoseVS-100 Center Channel Mini Speaker BOS 116.96 EA BOS Bose

18 rows selected.18 rows selected.

II JJ rows (tuples)rows (tuples), , N N ++ M M columns (attributes)columns (attributes)II JJ rows (tuples)rows (tuples), , N N ++ M M columns (attributes)columns (attributes)

ProductsProductsRS1B 2-way Bookshelf Speakers INF 188 PRRS1B 2-way Bookshelf Speakers INF 188 PRSM165 Bookshelf-sized Speakers INF 205 PRSM165 Bookshelf-sized Speakers INF 205 PRCC1M Center Channel Speaker INF 164 EACC1M Center Channel Speaker INF 164 EA100 Compact Speakers BOS 205 PR100 Compact Speakers BOS 205 PR201-IV Direct/Reflecting Speakers BOS 205 PR201-IV Direct/Reflecting Speakers BOS 205 PRVS-100 Center Channel Mini Speaker BOS 116.96 EAVS-100 Center Channel Mini Speaker BOS 116.96 EA

ProductsProductsRS1B 2-way Bookshelf Speakers INF 188 PRRS1B 2-way Bookshelf Speakers INF 188 PRSM165 Bookshelf-sized Speakers INF 205 PRSM165 Bookshelf-sized Speakers INF 205 PRCC1M Center Channel Speaker INF 164 EACC1M Center Channel Speaker INF 164 EA100 Compact Speakers BOS 205 PR100 Compact Speakers BOS 205 PR201-IV Direct/Reflecting Speakers BOS 205 PR201-IV Direct/Reflecting Speakers BOS 205 PRVS-100 Center Channel Mini Speaker BOS 116.96 EAVS-100 Center Channel Mini Speaker BOS 116.96 EA

ManufacturersManufacturersADV AdventADV AdventINF InfinityINF InfinityBOS BoseBOS Bose

ManufacturersManufacturersADV AdventADV AdventINF InfinityINF InfinityBOS BoseBOS Bose

3 3 xx 6 = 18 rows 6 = 18 rows3 3 xx 6 = 18 rows 6 = 18 rows

Page 11: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

11

R. Ching, Ph.D. • MIS • California State University, Sacramento

attribute-1, ..., attribute-attribute-1, ..., attribute-nn((RR) {) {-}-}attribute-1, ..., attribute-attribute-1, ..., attribute-nn((SS) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((RR) {) {-}-}attribute-1, ..., attribute-attribute-1, ..., attribute-nn((SS) )

Columns Columns mustmust correspond to one another correspond to one another

R R S S R R S S RR SS

Union, Intersection, Set DifferenceUnion, Intersection, Set Difference

SELECT colunn-name1, ..., column-namenSELECT colunn-name1, ..., column-namen

FROM table1FROM table1

{UNION | INTERSECT | MINUS}{UNION | INTERSECT | MINUS}

SELECT column-name1, ..., column-namenSELECT column-name1, ..., column-namen

FROM table2FROM table2

Page 12: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

12

R. Ching, Ph.D. • MIS • California State University, Sacramento

Example TablesExample Tables

TEAC_200_products;TEAC_200_products;

W-410C Double Cassette Deck TEA 89.96 EAW-410C Double Cassette Deck TEA 89.96 EAW-525R Auto-Reverse Double Cassette TEA 170.96 EAW-525R Auto-Reverse Double Cassette TEA 170.96 EAV-370 Cassette Deck TEA 63.86 EAV-370 Cassette Deck TEA 63.86 EAV-390CHX Cassette Deck TEA 89.96 EAV-390CHX Cassette Deck TEA 89.96 EAEQA-3 Stereo 10-Band Equalizer TEA 62.96 EAEQA-3 Stereo 10-Band Equalizer TEA 62.96 EAPD-555 CD Player TEA 116.96 EAPD-555 CD Player TEA 116.96 EAPD-C400 Remote CD Player TEA 152.96 EAPD-C400 Remote CD Player TEA 152.96 EA

7 Rows7 Rows

TEAC_200_products;TEAC_200_products;

W-410C Double Cassette Deck TEA 89.96 EAW-410C Double Cassette Deck TEA 89.96 EAW-525R Auto-Reverse Double Cassette TEA 170.96 EAW-525R Auto-Reverse Double Cassette TEA 170.96 EAV-370 Cassette Deck TEA 63.86 EAV-370 Cassette Deck TEA 63.86 EAV-390CHX Cassette Deck TEA 89.96 EAV-390CHX Cassette Deck TEA 89.96 EAEQA-3 Stereo 10-Band Equalizer TEA 62.96 EAEQA-3 Stereo 10-Band Equalizer TEA 62.96 EAPD-555 CD Player TEA 116.96 EAPD-555 CD Player TEA 116.96 EAPD-C400 Remote CD Player TEA 152.96 EAPD-C400 Remote CD Player TEA 152.96 EA

7 Rows7 Rows

TEAC_150_250_productsTEAC_150_250_products

W-525R Auto-Reverse Double Cassette TEA 170.96 EAW-525R Auto-Reverse Double Cassette TEA 170.96 EAW-585R Double Cassette Deck TEA 224.96 EAW-585R Double Cassette Deck TEA 224.96 EAPD-C400 Remote CD Player TEA 152.96 EAPD-C400 Remote CD Player TEA 152.96 EA

3 Rows3 Rows

TEAC_150_250_productsTEAC_150_250_products

W-525R Auto-Reverse Double Cassette TEA 170.96 EAW-525R Auto-Reverse Double Cassette TEA 170.96 EAW-585R Double Cassette Deck TEA 224.96 EAW-585R Double Cassette Deck TEA 224.96 EAPD-C400 Remote CD Player TEA 152.96 EAPD-C400 Remote CD Player TEA 152.96 EA

3 Rows3 Rows

Page 13: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

13

R. Ching, Ph.D. • MIS • California State University, Sacramento

UnionUnion

attribute-1, ..., attribute-attribute-1, ..., attribute-nn((RR) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((SS) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((RR) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((SS) )

SQL> select * from teac_200_productsSQL> select * from teac_200_products 2 union2 union 3 select * from teac_150_250_products;3 select * from teac_150_250_products;

EQA-3 Stereo 10-Band Equalizer TEA 62.96 EAEQA-3 Stereo 10-Band Equalizer TEA 62.96 EAPD-555 CD Player TEA 116.96 EAPD-555 CD Player TEA 116.96 EAPD-C400 Remote CD Player TEA 152.96 EAPD-C400 Remote CD Player TEA 152.96 EAV-370 Cassette Deck TEA 63.86 EAV-370 Cassette Deck TEA 63.86 EAV-390CHX Cassette Deck TEA 89.96 EAV-390CHX Cassette Deck TEA 89.96 EAW-410C Double Cassette Deck TEA 89.96 EAW-410C Double Cassette Deck TEA 89.96 EAW-525R Auto-Reverse Double Cassette TEA 170.96 EAW-525R Auto-Reverse Double Cassette TEA 170.96 EAW-585R Double Cassette Deck TEA 224.96 EAW-585R Double Cassette Deck TEA 224.96 EA

88 rows selected. rows selected. No duplicatesNo duplicates

Page 14: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

14

R. Ching, Ph.D. • MIS • California State University, Sacramento

IntersectionIntersection

SQL> select * from teac_200_productsSQL> select * from teac_200_products 2 intersect2 intersect 3 select * from teac_150_250_products;3 select * from teac_150_250_products;

PD-C400 Remote CD Player TEA 152.96 EAPD-C400 Remote CD Player TEA 152.96 EAW-525R Auto-Reverse Double Cassette TEA 170.96 EAW-525R Auto-Reverse Double Cassette TEA 170.96 EA

attribute-1, ..., attribute-attribute-1, ..., attribute-nn((RR) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((SS) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((RR) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((SS) )

Common between the two tablesCommon between the two tables

Page 15: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

15

R. Ching, Ph.D. • MIS • California State University, Sacramento

Set DifferenceSet Difference

attribute-1, ..., attribute-attribute-1, ..., attribute-nn((RR) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((SS) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((RR) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((SS) )

• Performed on two Performed on two union compatibleunion compatible tables (i.e., same tables (i.e., same columns)columns)

• Displays the rows unique to one of the two tables (i.e., Displays the rows unique to one of the two tables (i.e., found in one but not the other)found in one but not the other)

– The order of the tables matters!The order of the tables matters!

Page 16: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

16

R. Ching, Ph.D. • MIS • California State University, Sacramento

Set DifferenceSet Difference

SQL> SQL> select * from teac_200_productsselect * from teac_200_products 2 2 minusminus 3 3 select * from teac_150_250_products;select * from teac_150_250_products;

EQA-3 Stereo 10-Band Equalizer TEA 62.96 EAEQA-3 Stereo 10-Band Equalizer TEA 62.96 EAPD-555 CD Player TEA 116.96 EAPD-555 CD Player TEA 116.96 EAV-370 Cassette Deck TEA 63.86 EAV-370 Cassette Deck TEA 63.86 EAV-390CHX Cassette Deck TEA 89.96 EAV-390CHX Cassette Deck TEA 89.96 EAW-410C Double Cassette Deck TEA 89.96 EAW-410C Double Cassette Deck TEA 89.96 EA

attribute-1, ..., attribute-attribute-1, ..., attribute-nn((RR) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((SS) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((RR) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((SS) )

SQLSQL>> select * from teac_150_250_productsselect * from teac_150_250_products 2 2 minusminus 3 3 select * from teac_200_products;select * from teac_200_products;

W-585R Double Cassette Deck TEA 224.96 EAW-585R Double Cassette Deck TEA 224.96 EA

Why?Why?

Page 17: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

17

R. Ching, Ph.D. • MIS • California State University, Sacramento

Set DifferenceSet Difference

SQL> SQL> select * from teac_200_productsselect * from teac_200_products 2 2 minusminus 3 3 select * from teac_150_250_products;select * from teac_150_250_products;

EQA-3 Stereo 10-Band Equalizer TEA 62.96 EAEQA-3 Stereo 10-Band Equalizer TEA 62.96 EAPD-555 CD Player TEA 116.96 EAPD-555 CD Player TEA 116.96 EAV-370 Cassette Deck TEA 63.86 EAV-370 Cassette Deck TEA 63.86 EAV-390CHX Cassette Deck TEA 89.96 EAV-390CHX Cassette Deck TEA 89.96 EAW-410C Double Cassette Deck TEA 89.96 EAW-410C Double Cassette Deck TEA 89.96 EA

attribute-1, ..., attribute-attribute-1, ..., attribute-nn((RR) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((SS) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((RR) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((SS) )

TEAC_200_productsTEAC_200_products;;

W-410CW-410CW-525RW-525RV-370V-370V-390CHXV-390CHXEQA-3 EQA-3 PD-555PD-555PD-C400PD-C400

TEAC_200_productsTEAC_200_products;;

W-410CW-410CW-525RW-525RV-370V-370V-390CHXV-390CHXEQA-3 EQA-3 PD-555PD-555PD-C400PD-C400

TEAC_150_250_productsTEAC_150_250_products

W-525R W-525R W-585RW-585RPD-C400PD-C400

TEAC_150_250_productsTEAC_150_250_products

W-525R W-525R W-585RW-585RPD-C400PD-C400

7 Rows7 Rows

3 Rows3 Rows

These rows are unique to TEAC_200_products

Duplicates

Page 18: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

18

R. Ching, Ph.D. • MIS • California State University, Sacramento

Set DifferenceSet Difference

attribute-1, ..., attribute-attribute-1, ..., attribute-nn((RR) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((SS) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((RR) ) attribute-1, ..., attribute-attribute-1, ..., attribute-nn((SS) )

SQL> SQL> select * from teac_150_250_productsselect * from teac_150_250_products 2 2 minusminus 3 3 select * from teac_200_products;select * from teac_200_products;

W-585R Double Cassette Deck TEA 224.96 EAW-585R Double Cassette Deck TEA 224.96 EA

TEAC_200_productsTEAC_200_products;;

W-410CW-410CW-525RW-525RV-370V-370V-390CHXV-390CHXEQA-3 EQA-3 PD-555PD-555PD-C400PD-C400

TEAC_200_productsTEAC_200_products;;

W-410CW-410CW-525RW-525RV-370V-370V-390CHXV-390CHXEQA-3 EQA-3 PD-555PD-555PD-C400PD-C400

TEAC_150_250_productsTEAC_150_250_products

W-525R W-525R W-585RW-585RPD-C400PD-C400

TEAC_150_250_productsTEAC_150_250_products

W-525R W-525R W-585RW-585RPD-C400PD-C400

7 Rows7 Rows

3 Rows3 Rows

This rows is unique to TEAC_150_250_products

Duplicates

Page 19: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

19

R. Ching, Ph.D. • MIS • California State University, Sacramento

Calculation and Format Models (Masks)Calculation and Format Models (Masks)

SQL> select product_code,SQL> select product_code, 2 2 manufacturer_name || ' - ' || product_descriptionmanufacturer_name || ' - ' || product_description 3 as "Description",3 as "Description", 4 number_on_hand as "Stock on Hand", 4 number_on_hand as "Stock on Hand", 5 to_char(product_retail_price,'$9,990.00') as "Selling Price",5 to_char(product_retail_price,'$9,990.00') as "Selling Price", 6 to_char(6 to_char(number_on_hand * product_retail_pricenumber_on_hand * product_retail_price,'$9,990.00'),'$9,990.00') 7 as "Inventory Value"7 as "Inventory Value" 8 from products p, manufacturers m8 from products p, manufacturers m 9 where p.manufacturer_code = m.manufacturer_code9 where p.manufacturer_code = m.manufacturer_code 10 and product_retail_price < 100;10 and product_retail_price < 100; Format Format

modelmodel

AliasAlias

ConcatenationConcatenation

Converts numeric or date data type to characterConverts numeric or date data type to character(required for a format mask)(required for a format mask)

Page 20: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

20

R. Ching, Ph.D. • MIS • California State University, Sacramento

Calculation and Format Models (Masks)Calculation and Format Models (Masks)(Results)(Results)

PRODUCT_CO Description Stock on Hand Selling Pr InventoryPRODUCT_CO Description Stock on Hand Selling Pr Inventory---------- --------------------------------------------- ----------------------- --------------------------------------------- -------------XL-BD10 Gemini - Semi-Auto Belt-Dr Turntable 1 $80.96 $80.96XL-BD10 Gemini - Semi-Auto Belt-Dr Turntable 1 $80.96 $80.96V-370 Teac - Cassette Deck 1 $63.86 $63.86V-370 Teac - Cassette Deck 1 $63.86 $63.86V-390CHX Teac - Cassette Deck 1 $89.96 $89.96V-390CHX Teac - Cassette Deck 1 $89.96 $89.96W-410C Teac - Double Cassette Deck 1 $89.96 $89.96W-410C Teac - Double Cassette Deck 1 $89.96 $89.96SH-8017 Technics - Graphic Equalizer 1 $62.96 $62.96SH-8017 Technics - Graphic Equalizer 1 $62.96 $62.96SL-BD20 Technics - Belt-Drive Semi-Auto Turntabl 1 $89.96 $89.96SL-BD20 Technics - Belt-Drive Semi-Auto Turntabl 1 $89.96 $89.96EQA-3 Teac - Stereo 10-Band Equalizer 1 $62.96 $62.96EQA-3 Teac - Stereo 10-Band Equalizer 1 $62.96 $62.96CD-1000C Sherwood - Compact Disc Changer 1 $89.96 $89.96CD-1000C Sherwood - Compact Disc Changer 1 $89.96 $89.96

8 rows selected.8 rows selected.

(Edited to fit the slide)(Edited to fit the slide)

Page 21: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

21

R. Ching, Ph.D. • MIS • California State University, Sacramento

Applicable ColumnsApplicable Columns

SQL> describe products;SQL> describe products; Name Null? TypeName Null? Type --------------------------------------- -------- ---------------------------------------------------- -------- ------------- PRODUCT_CODE NOT NULL VARCHAR2(10)PRODUCT_CODE NOT NULL VARCHAR2(10) PRODUCT_DESCRIPTION VARCHAR2(35)PRODUCT_DESCRIPTION VARCHAR2(35) PRODUCT_COST NUMBER(8,2)PRODUCT_COST NUMBER(8,2) PRODUCT_MSRP NUMBER(8,2)PRODUCT_MSRP NUMBER(8,2) PRODUCT_RETAIL_PRICE NUMBER(8,2)PRODUCT_RETAIL_PRICE NUMBER(8,2) RETAIL_UNIT CHAR(2)RETAIL_UNIT CHAR(2) MANUFACTURER_CODE CHAR(3)MANUFACTURER_CODE CHAR(3) ACTIVE_DATE DATEACTIVE_DATE DATE NUMBER_ON_HAND NUMBER(6)NUMBER_ON_HAND NUMBER(6) NUMBER_ON_ORDER NUMBER(6)NUMBER_ON_ORDER NUMBER(6) NUMBER_COMMITTED NUMBER(6)NUMBER_COMMITTED NUMBER(6) INACTIVE_DATE DATEINACTIVE_DATE DATE

SQL> describe manufacturers;SQL> describe manufacturers; Name Null? TypeName Null? Type --------------------------------------- -------- ---------------------------------------------------- -------- ------------- MANUFACTURER_CODE NOT NULL CHAR(3)MANUFACTURER_CODE NOT NULL CHAR(3) MANUFACTURER_NAME NOT NULL VARCHAR2(30)MANUFACTURER_NAME NOT NULL VARCHAR2(30)

Page 22: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

22

R. Ching, Ph.D. • MIS • California State University, Sacramento

SQL> select manufacturer_name, sum(number_on_hand),SQL> select manufacturer_name, sum(number_on_hand), 2 max(product_retail_price),min(product_retail_price),2 max(product_retail_price),min(product_retail_price), 3 avg(product_retail_price),count(product_code)3 avg(product_retail_price),count(product_code) 4 from products p, manufacturers m4 from products p, manufacturers m 5 where p.manufacturer_code = m.manufacturer_code5 where p.manufacturer_code = m.manufacturer_code 6 group by manufacturer_name6 group by manufacturer_name 7 having sum(number_on_hand) > 257 having sum(number_on_hand) > 25 8 order by manufacturer_name;8 order by manufacturer_name;

MANUFACTURER_NAME SUM(NUMBER_ON_HAND) MAX(PRODUCT_RETAIL_PRICE)MANUFACTURER_NAME SUM(NUMBER_ON_HAND) MAX(PRODUCT_RETAIL_PRICE)-------------------- ------------------- --------------------------------------------- ------------------- -------------------------MIN(PRODUCT_RETAIL_PRICE) AVG(PRODUCT_RETAIL_PRICE) COUNT(PRODUCT_CODE)MIN(PRODUCT_RETAIL_PRICE) AVG(PRODUCT_RETAIL_PRICE) COUNT(PRODUCT_CODE)------------------------- ------------------------- -------------------------------------------- ------------------------- -------------------JVC 30 1266JVC 30 1266 116.96 417.31867 30116.96 417.31867 30

Polk 26 1614Polk 26 1614 135 427.07692 26135 427.07692 26

Sony 68 2474Sony 68 2474 116.96 561.34426 68116.96 561.34426 68

Technics 32 629.96Technics 32 629.96 62.96 200.97625 3262.96 200.97625 32

Do not follow this query too closely for your homework assignmentDo not follow this query too closely for your homework assignmentDo not follow this query too closely for your homework assignmentDo not follow this query too closely for your homework assignment

Page 23: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

23

R. Ching, Ph.D. • MIS • California State University, Sacramento

Do not follow this query too closely for your homework assignmentDo not follow this query too closely for your homework assignmentDo not follow this query too closely for your homework assignmentDo not follow this query too closely for your homework assignment

SQL> select manufacturer_name manufacturer,SQL> select manufacturer_name manufacturer, 2 to_char(sum(number_on_hand),'9,990')"Total on Hand",2 to_char(sum(number_on_hand),'9,990')"Total on Hand", 3 to_char(max(product_retail_price),'$9,990.00') "Max Price",3 to_char(max(product_retail_price),'$9,990.00') "Max Price", 4 to_char(min(product_retail_price),'$9,990.00') "Min Price",4 to_char(min(product_retail_price),'$9,990.00') "Min Price", 5 to_char(avg(product_retail_price),'$9,990.00')5 to_char(avg(product_retail_price),'$9,990.00') 6 "Average Price",6 "Average Price", 7 to_char(count(product_code),'9,990') "Total Products"7 to_char(count(product_code),'9,990') "Total Products" 8 from products p, manufacturers m8 from products p, manufacturers m 9 where p.manufacturer_code = m.manufacturer_code9 where p.manufacturer_code = m.manufacturer_code 10 group by manufacturer_name10 group by manufacturer_name 11 having sum(number_on_hand) > 2511 having sum(number_on_hand) > 25 12 order by manufacturer_name;12 order by manufacturer_name;

MANUFACTURER Total Max Price Min Price Average Pr TotalMANUFACTURER Total Max Price Min Price Average Pr Total----------------- ------ ---------- ---------- ---------- ----------------------- ------ ---------- ---------- ---------- ------JVC 30 $1,266.00 $116.96 $417.32 30JVC 30 $1,266.00 $116.96 $417.32 30Polk 26 $1,614.00 $135.00 $427.08 26Polk 26 $1,614.00 $135.00 $427.08 26Sony 68 $2,474.00 $116.96 $561.34 68Sony 68 $2,474.00 $116.96 $561.34 68Technics 32 $629.96 $62.96 $200.98 32Technics 32 $629.96 $62.96 $200.98 32

Output edited to fit slideOutput edited to fit slide

Page 24: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

24

R. Ching, Ph.D. • MIS • California State University, Sacramento

Et cetera:Et cetera: Changing Column Titles Changing Column TitlesUsing a Column AliasUsing a Column Alias

SQL> SQL> select po_number select po_number as "PO"as "PO",, 2 2 to_char(po_date,'fmMonth dd, yyyy') to_char(po_date,'fmMonth dd, yyyy') as "PO Date"as "PO Date",, 3 3 to_char(total_amount,'999,990.00') to_char(total_amount,'999,990.00') as "Total Amount"as "Total Amount" 4 4 from purchase_ordersfrom purchase_orders 5 5 where po_date > (sysdate - 45);where po_date > (sysdate - 45);

PO PO Date Total AmounPO PO Date Total Amoun----- ------------------ ---------------- ------------------ -----------10018 September 11, 1999 36,189.0510018 September 11, 1999 36,189.0510019 September 18, 1999 5,394.4010019 September 18, 1999 5,394.4010020 September 25, 1999 15,313.6510020 September 25, 1999 15,313.6510021 October 2, 1999 25,470.1510021 October 2, 1999 25,470.1510022 October 9, 1999 1,949.7010022 October 9, 1999 1,949.70

Page 25: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

25

R. Ching, Ph.D. • MIS • California State University, Sacramento

Substring, Truncation, Modulus:Substring, Truncation, Modulus:

SUBSTR, TRUN, MODSUBSTR, TRUN, MOD

SQL> select product_code, 2 substr(manufacturer_name||' - '||product_description, 3 1,35) as "Product", 4 substr(to_char(active_date,'fmMonth yyyy'),1,12) 5 as "Active Date", 6 substr(to_char(sysdate,'fmMonth yyyy'),1,12) 7 as "Current Date", 8 trunc((sysdate-active_date)/365.25,0) as "Years", 9 trunc(mod(sysdate-active_date,365.25)/30,0) 10 as "Months" 11 from products p, manufacturers m 12 where p.manufacturer_code=m.manufacturer_code 13 and lower(product_description) like '%cd%';

Page 26: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

26

R. Ching, Ph.D. • MIS • California State University, Sacramento

Substring, Truncation, Modulus:Substring, Truncation, Modulus:

SUBSTR, TRUN, MODSUBSTR, TRUN, MOD

SQL> select product_code, 2 substr(manufacturer_name||' - '||product_description, 3 1,35) as "Product", 4 substr(to_char(active_date,'fmMonth yyyy'),1,12) 5 as "Active Date", 6 substr(to_char(sysdate,'fmMonth yyyy'),1,12) 7 as "Current Date", 8 trunc((sysdate-active_date)/365.25,0) as "Years", 9 trunc(mod(sysdate-active_date,365.25)/30,0) 10 as "Months" 11 from products p, manufacturers m 12 where p.manufacturer_code=m.manufacturer_code 13 and lower(product_description) like '%cd%';

SUBSTRSUBSTR (substring): Selects a portion (substring): Selects a portion of the string as specified by the of the string as specified by the beginning position and length argumentsbeginning position and length arguments

SUBSTR(SUBSTR(stringstring,,begin-positionbegin-position,,lengthlength))

SUBSTRSUBSTR (substring): Selects a portion (substring): Selects a portion of the string as specified by the of the string as specified by the beginning position and length argumentsbeginning position and length arguments

SUBSTR(SUBSTR(stringstring,,begin-positionbegin-position,,lengthlength))

Page 27: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

27

R. Ching, Ph.D. • MIS • California State University, Sacramento

Substring, Truncation, Modulus:Substring, Truncation, Modulus:

SUBSTR, TRUN, MODSUBSTR, TRUN, MOD

SQL> select product_code, 2 substr(manufacturer_name||' - '||product_description, 3 1,35) as "Product", 4 substr(to_char(active_date,'fmMonth yyyy'),1,12) 5 as "Active Date", 6 substr(to_char(sysdate,'fmMonth yyyy'),1,12) 7 as "Current Date", 8 trunc((sysdate-active_date)/365.25,0) as "Years", 9 trunc(mod(sysdate-active_date,365.25)/30,0) 10 as "Months" 11 from products p, manufacturers m 12 where p.manufacturer_code=m.manufacturer_code 13 and lower(product_description) like '%cd%';

TRUNCTRUNC (truncate): Prevents rounding in arithmetic operations. (truncate): Prevents rounding in arithmetic operations.

TRUNC(TRUNC(arithmetic-operationarithmetic-operation,,decimal-placesdecimal-places))

TRUNCTRUNC (truncate): Prevents rounding in arithmetic operations. (truncate): Prevents rounding in arithmetic operations.

TRUNC(TRUNC(arithmetic-operationarithmetic-operation,,decimal-placesdecimal-places))

Page 28: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

28

R. Ching, Ph.D. • MIS • California State University, Sacramento

Substring, Truncation, Modulus:Substring, Truncation, Modulus:

SUBSTR, TRUN, MODSUBSTR, TRUN, MOD

SQL> select product_code, 2 substr(manufacturer_name||' - '||product_description, 3 1,35) as "Product", 4 substr(to_char(active_date,'fmMonth yyyy'),1,12) 5 as "Active Date", 6 substr(to_char(sysdate,'fmMonth yyyy'),1,12) 7 as "Current Date", 8 trunc((sysdate-active_date)/365.25,0) as "Years", 9 trunc(mod(sysdate-active_date,365.25)/30,0) 10 as "Months" 11 from products p, manufacturers m 12 where p.manufacturer_code=m.manufacturer_code 13 and lower(product_description) like '%cd%';

MODMOD (modulus): Retains the remainder in division. (modulus): Retains the remainder in division.

MOD(MOD(numeratornumerator,,denominatordenominator))

MODMOD (modulus): Retains the remainder in division. (modulus): Retains the remainder in division.

MOD(MOD(numeratornumerator,,denominatordenominator))

Part of TRUNC argumentPart of TRUNC argument

Page 29: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

29

R. Ching, Ph.D. • MIS • California State University, Sacramento

PRODUCT_CO Product Active Date Current Date Years Months---------- ----------------------------------- ------------ ------------ --------- ---------DVD-A110 Panasonic - DVD/CD Player May 1998 March 2001 2 10DV-505 Pioneer - DVD/CD Player May 1998 March 2001 2 10XV-1000BK JVC - DVD/CD Player May 1998 March 2001 2 10DVL-909 Pioneer - DVD/CD/Laserdisc Player May 1998 March 2001 2 10DVP-S7000 Sony - DVD/CD Player May 1998 March 2001 2 10DVP-S3000 Sony - DVD/CD Player May 1998 March 2001 2 10DVP-S500D Sony - DVD/CD Player May 1998 March 2001 2 10SC-TC430 Panasonic - Compact System w/CD Cha August 1996 March 2001 4 6CCS-350 Pioneer - Compact System w/CD Playe August 1996 March 2001 4 6CCS-450 Pioneer - Compact System w/CD Playe August 1996 March 2001 4 6CCS-550 Pioneer - 75-watt System w/CD Chang August 1996 March 2001 4 6CDP-C225 Sony - Disc Jockey CD Changer August 1996 March 2001 4 6CDP-C325 Sony - Disc Jockey CD Changer August 1996 March 2001 4 6CDP-C425 Sony - Disc Jockey CD Changer August 1996 March 2001 4 6CDP-C525 Sony - Disc Jockey CD Changer August 1996 March 2001 4 6PD-F907 Pioneer - 100+1 Disc CD Changer May 1998 March 2001 2 10PD-F957 Pioneer - 100+1 Disc CD Changer May 1998 March 2001 2 10CDC-502 Yamaha - 5-Disc Carousel CD Changer May 1998 March 2001 2 10CDC-902 Yamaha - 5-Disc Carousel CD Changer May 1998 March 2001 2 10XL-F154 JVC - 5-Disc CD Changer May 1998 March 2001 2 10XL-F254 JVC - 5-Disc CD Changer May 1998 March 2001 2 10XL-MC222 JVC - 200-Disc CD Changer May 1998 March 2001 2 10XL-MC334 JVC - 200-Disc CD Changer May 1998 March 2001 2 10CD-223M Kenwood - 200-Disc CD Changer May 1998 March 2001 2 10CD-224M Kenwood - 200-Disc CD Changer May 1998 March 2001 2 10SL-PD788 Technics - 5-Disc CD Changer May 1998 March 2001 2 10SL-PD888 Technics - 5-Disc CD Changer May 1998 March 2001 2 10SL-PD988 Technics - 5-Disc CD Changer May 1998 March 2001 2 10 . . .

PD-F407 Pioneer - 25-Disc CD Changer May 1998 March 2001 2 10PD-F507 Pioneer - 25-Disc CD Changer May 1998 March 2001 2 10PD-F607 Pioneer - 25-Disc CD Changer May 1998 March 2001 2 10

48 rows selected.

Page 30: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

30

R. Ching, Ph.D. • MIS • California State University, Sacramento

Applicable ColumnsApplicable Columns

SQL> describe products;SQL> describe products; Name Null? TypeName Null? Type --------------------------------------- -------- ---------------------------------------------------- -------- ------------- PRODUCT_CODE NOT NULL VARCHAR2(10)PRODUCT_CODE NOT NULL VARCHAR2(10) PRODUCT_DESCRIPTION VARCHAR2(35)PRODUCT_DESCRIPTION VARCHAR2(35) PRODUCT_COST NUMBER(8,2)PRODUCT_COST NUMBER(8,2) PRODUCT_MSRP NUMBER(8,2)PRODUCT_MSRP NUMBER(8,2) PRODUCT_RETAIL_PRICE NUMBER(8,2)PRODUCT_RETAIL_PRICE NUMBER(8,2) RETAIL_UNIT CHAR(2)RETAIL_UNIT CHAR(2) MANUFACTURER_CODE CHAR(3)MANUFACTURER_CODE CHAR(3) ACTIVE_DATE DATEACTIVE_DATE DATE NUMBER_ON_HAND NUMBER(6)NUMBER_ON_HAND NUMBER(6) NUMBER_ON_ORDER NUMBER(6)NUMBER_ON_ORDER NUMBER(6) NUMBER_COMMITTED NUMBER(6)NUMBER_COMMITTED NUMBER(6) INACTIVE_DATE DATEINACTIVE_DATE DATE

SQL> describe manufacturers;SQL> describe manufacturers; Name Null? TypeName Null? Type --------------------------------------- -------- ---------------------------------------------------- -------- ------------- MANUFACTURER_CODE NOT NULL CHAR(3)MANUFACTURER_CODE NOT NULL CHAR(3) MANUFACTURER_NAME NOT NULL VARCHAR2(30)MANUFACTURER_NAME NOT NULL VARCHAR2(30)

Page 31: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

31

R. Ching, Ph.D. • MIS • California State University, Sacramento

Aggregation FunctionsAggregation Functions

• Summation (SUM)Summation (SUM)

• Count (COUNT)Count (COUNT)

• Average value (AVG)Average value (AVG)

• Maximum value (MAX)Maximum value (MAX)

• Minimum value (MIN)Minimum value (MIN)

Page 32: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

32

R. Ching, Ph.D. • MIS • California State University, Sacramento

SQL> select manufacturer_name, sum(number_on_hand),SQL> select manufacturer_name, sum(number_on_hand), 2 max(product_retail_price),min(product_retail_price),2 max(product_retail_price),min(product_retail_price), 3 avg(product_retail_price),count(product_code)3 avg(product_retail_price),count(product_code) 4 from products p, manufacturers m4 from products p, manufacturers m 5 where p.manufacturer_code = m.manufacturer_code5 where p.manufacturer_code = m.manufacturer_code 6 group by manufacturer_name6 group by manufacturer_name 7 having sum(number_on_hand) > 257 having sum(number_on_hand) > 25 8 order by manufacturer_name;8 order by manufacturer_name;

MANUFACTURER_NAME SUM(NUMBER_ON_HAND) MAX(PRODUCT_RETAIL_PRICE)MANUFACTURER_NAME SUM(NUMBER_ON_HAND) MAX(PRODUCT_RETAIL_PRICE)-------------------- ------------------- --------------------------------------------- ------------------- -------------------------MIN(PRODUCT_RETAIL_PRICE) AVG(PRODUCT_RETAIL_PRICE) COUNT(PRODUCT_CODE)MIN(PRODUCT_RETAIL_PRICE) AVG(PRODUCT_RETAIL_PRICE) COUNT(PRODUCT_CODE)------------------------- ------------------------- -------------------------------------------- ------------------------- -------------------JVC 30 1266JVC 30 1266 116.96 417.31867 30116.96 417.31867 30

Polk 26 1614Polk 26 1614 135 427.07692 26135 427.07692 26

Sony 68 2474Sony 68 2474 116.96 561.34426 68116.96 561.34426 68

Technics 32 629.96Technics 32 629.96 62.96 200.97625 3262.96 200.97625 32

Do not follow this query too closely for your homework assignmentDo not follow this query too closely for your homework assignmentDo not follow this query too closely for your homework assignmentDo not follow this query too closely for your homework assignment

Page 33: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

33

R. Ching, Ph.D. • MIS • California State University, Sacramento

Do not follow this query too closely for your homework assignmentDo not follow this query too closely for your homework assignmentDo not follow this query too closely for your homework assignmentDo not follow this query too closely for your homework assignment

SQL> select manufacturer_name manufacturer,SQL> select manufacturer_name manufacturer, 2 to_char(sum(number_on_hand),'9,990')"Total on Hand",2 to_char(sum(number_on_hand),'9,990')"Total on Hand", 3 to_char(max(product_retail_price),'$9,990.00') "Max Price",3 to_char(max(product_retail_price),'$9,990.00') "Max Price", 4 to_char(min(product_retail_price),'$9,990.00') "Min Price",4 to_char(min(product_retail_price),'$9,990.00') "Min Price", 5 to_char(avg(product_retail_price),'$9,990.00')5 to_char(avg(product_retail_price),'$9,990.00') 6 "Average Price",6 "Average Price", 7 to_char(count(product_code),'9,990') "Total Products"7 to_char(count(product_code),'9,990') "Total Products" 8 from products p, manufacturers m8 from products p, manufacturers m 9 where p.manufacturer_code = m.manufacturer_code9 where p.manufacturer_code = m.manufacturer_code 10 group by manufacturer_name10 group by manufacturer_name 11 having sum(number_on_hand) > 2511 having sum(number_on_hand) > 25 12 order by manufacturer_name;12 order by manufacturer_name;

MANUFACTURER Total Max Price Min Price Average Pr TotalMANUFACTURER Total Max Price Min Price Average Pr Total----------------- ------ ---------- ---------- ---------- ----------------------- ------ ---------- ---------- ---------- ------JVC 30 $1,266.00 $116.96 $417.32 30JVC 30 $1,266.00 $116.96 $417.32 30Polk 26 $1,614.00 $135.00 $427.08 26Polk 26 $1,614.00 $135.00 $427.08 26Sony 68 $2,474.00 $116.96 $561.34 68Sony 68 $2,474.00 $116.96 $561.34 68Technics 32 $629.96 $62.96 $200.98 32Technics 32 $629.96 $62.96 $200.98 32

Output edited to fit slideOutput edited to fit slide

Page 34: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

34

R. Ching, Ph.D. • MIS • California State University, Sacramento

SubquerySubquery

• Embeds a complete SELECT statement (inner query) Embeds a complete SELECT statement (inner query) within another SELECT statement (outer query)within another SELECT statement (outer query)

• Subquery types:Subquery types:

– Scalar - returns a single column and row (i.e., single Scalar - returns a single column and row (i.e., single value) value)

– Row - returns multiple columns, but a single rowRow - returns multiple columns, but a single row

– Table - returns one or more columns and multiple rowsTable - returns one or more columns and multiple rows

Page 35: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

35

R. Ching, Ph.D. • MIS • California State University, Sacramento

Scalar SubqueryScalar Subquery

SQL> select product_code, product_descriptionSQL> select product_code, product_description 2 from products 2 from products 3 where manufacturer_code =3 where manufacturer_code = 4 (select manufacturer_code 4 (select manufacturer_code 5 from manufacturers5 from manufacturers 6 where manufacturer_name = 'Bose');6 where manufacturer_name = 'Bose');

Returns only one Returns only one value (i.e., one value (i.e., one manufacturer_code)manufacturer_code)

Page 36: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

36

R. Ching, Ph.D. • MIS • California State University, Sacramento

As Single QueriesAs Single Queries

SQL> select manufacturer_code SQL> select manufacturer_code 2 from manufacturers2 from manufacturers 3 where manufacturer_name = 'Bose';3 where manufacturer_name = 'Bose';

MANMAN------BOSBOS

Page 37: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

37

R. Ching, Ph.D. • MIS • California State University, Sacramento

SQL> select product_code, product_descriptionSQL> select product_code, product_description 2 from products 2 from products 3 where manufacturer_code = 'BOS';3 where manufacturer_code = 'BOS';

PRODUCT_CO PRODUCT_DESCRIPTIONPRODUCT_CO PRODUCT_DESCRIPTION---------- --------------------------------------------- -----------------------------------VS-100 Center Channel Mini SpeakerVS-100 Center Channel Mini Speaker301-III Direct/Reflecting Speakers301-III Direct/Reflecting Speakers901Classic Direct/Reflecting Speaker System901Classic Direct/Reflecting Speaker SystemAM3 Acoustimass Speaker SystemAM3 Acoustimass Speaker SystemAM5 Acoustimass 5 Speaker SystemAM5 Acoustimass 5 Speaker SystemAM7 Acoustimass 7 Speaker SystemAM7 Acoustimass 7 Speaker SystemAM5II Accoustimass-5 Series II SpeakersAM5II Accoustimass-5 Series II SpeakersAM6 Accoustimass-6 Speaker SystemAM6 Accoustimass-6 Speaker SystemAM10 Accoustimass-10 Speaker SystemAM10 Accoustimass-10 Speaker SystemLS5 Lifestyle 5 II Speaker SystemLS5 Lifestyle 5 II Speaker SystemLS12 Lifestyle 12 Compact Speaker SystemLS12 Lifestyle 12 Compact Speaker SystemLS25 Lifestyle 25 Home Theater SpeakersLS25 Lifestyle 25 Home Theater Speakers100 Compact Speakers100 Compact Speakers201-IV Direct/Reflecting Speakers201-IV Direct/Reflecting Speakers301-IV Direct/Reflecting Speakers301-IV Direct/Reflecting Speakers501-V Floor Direct/Reflecting Speakers501-V Floor Direct/Reflecting Speakers701 Tower Speakers701 Tower Speakers

17 rows selected.17 rows selected.

Page 38: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

38

R. Ching, Ph.D. • MIS • California State University, Sacramento

SQL> select product_code, product_descriptionSQL> select product_code, product_description 2 from products 2 from products 3 where manufacturer_code =3 where manufacturer_code = 4 (select manufacturer_code 4 (select manufacturer_code 5 from manufacturers5 from manufacturers 6 where manufacturer_name = 'Bose');6 where manufacturer_name = 'Bose');

PRODUCT_CO PRODUCT_DESCRIPTIONPRODUCT_CO PRODUCT_DESCRIPTION---------- --------------------------------------------- -----------------------------------VS-100 Center Channel Mini SpeakerVS-100 Center Channel Mini Speaker301-III Direct/Reflecting Speakers301-III Direct/Reflecting Speakers901Classic Direct/Reflecting Speaker System901Classic Direct/Reflecting Speaker SystemAM3 Acoustimass Speaker SystemAM3 Acoustimass Speaker SystemAM5 Acoustimass 5 Speaker SystemAM5 Acoustimass 5 Speaker SystemAM7 Acoustimass 7 Speaker SystemAM7 Acoustimass 7 Speaker SystemAM5II Accoustimass-5 Series II SpeakersAM5II Accoustimass-5 Series II SpeakersAM6 Accoustimass-6 Speaker SystemAM6 Accoustimass-6 Speaker SystemAM10 Accoustimass-10 Speaker SystemAM10 Accoustimass-10 Speaker SystemLS5 Lifestyle 5 II Speaker SystemLS5 Lifestyle 5 II Speaker SystemLS12 Lifestyle 12 Compact Speaker SystemLS12 Lifestyle 12 Compact Speaker SystemLS25 Lifestyle 25 Home Theater SpeakersLS25 Lifestyle 25 Home Theater Speakers100 Compact Speakers100 Compact Speakers201-IV Direct/Reflecting Speakers201-IV Direct/Reflecting Speakers301-IV Direct/Reflecting Speakers301-IV Direct/Reflecting Speakers501-V Floor Direct/Reflecting Speakers501-V Floor Direct/Reflecting Speakers701 Tower Speakers701 Tower Speakers

17 rows selected.17 rows selected.

All Bose All Bose productsproducts

Results of Results of the inner the inner query are query are ‘fed’ to the ‘fed’ to the outer queryouter query

Inner Inner queryquery

Outer Outer queryquery

Page 39: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

39

R. Ching, Ph.D. • MIS • California State University, Sacramento

Non-scalar SubqueryNon-scalar Subquery

SQL> select product_code, product_descriptionSQL> select product_code, product_description 2 from products2 from products 3 where manufacturer_code =3 where manufacturer_code = 4 (select manufacturer_code4 (select manufacturer_code 5 from manufacturers5 from manufacturers 6 where manufacturer_name 6 where manufacturer_name in ('Bose','JBL','Advent')in ('Bose','JBL','Advent')););(select manufacturer_code(select manufacturer_code **ERROR at line 4:ERROR at line 4:ORA-01427: ORA-01427: single-row subquery returns more than one rowsingle-row subquery returns more than one row

Returns more than one valueReturns more than one value

Page 40: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

40

R. Ching, Ph.D. • MIS • California State University, Sacramento

Table SubqueriesTable Subqueries

• EXISTS and NOT EXISTSEXISTS and NOT EXISTS

– EXISTS - at least east one row exists in the subset EXISTS - at least east one row exists in the subset returned by the subqueryreturned by the subquery

– NOT EXISTS - all rows that do not exist in the subset NOT EXISTS - all rows that do not exist in the subset returned by the subqueryreturned by the subquery

• ANY/SOME and ALLANY/SOME and ALL

– ANY - any value produced by the subquery (i.e., one or ANY - any value produced by the subquery (i.e., one or more rows) can be satisfiedmore rows) can be satisfied

– ALL - all values of the subquery must be satisfiedALL - all values of the subquery must be satisfied

Page 41: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

41

R. Ching, Ph.D. • MIS • California State University, Sacramento

NOT EXISTS versus EXISTSNOT EXISTS versus EXISTS

NOT EXISTSNOT EXISTSSQL> select product_code, product_description, manufacturer_codeSQL> select product_code, product_description, manufacturer_code 2 from products p2 from products p 3 where 3 where not existsnot exists 4 (select * from manufacturers m4 (select * from manufacturers m 5 where p.manufacturer_code = m.manufacturer_code5 where p.manufacturer_code = m.manufacturer_code 6 and manufacturer_code > 'C')6 and manufacturer_code > 'C') 7 order by p.manufacturer_code;7 order by p.manufacturer_code;

EXISTSEXISTSSQL> select product_code, product_description, manufacturer_codeSQL> select product_code, product_description, manufacturer_code 2 from products p where 2 from products p where EXISTSEXISTS 3 (select * from manufacturers m3 (select * from manufacturers m 4 where manufacturer_name like 'C%' and4 where manufacturer_name like 'C%' and 5 p.manufacturer_code = m.manufacturer_code)5 p.manufacturer_code = m.manufacturer_code) 6 order by p.manufacturer_code, product_code;6 order by p.manufacturer_code, product_code;

Note. These queries can also be accomplished without the subquery.Note. These queries can also be accomplished without the subquery.

Page 42: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

42

R. Ching, Ph.D. • MIS • California State University, Sacramento

SQL> select product_code, product_description, manufacturer_codeSQL> select product_code, product_description, manufacturer_code 2 from products p2 from products p 3 where 3 where not existsnot exists 4 (select * from manufacturers m4 (select * from manufacturers m 5 where p.manufacturer_code = m.manufacturer_code5 where p.manufacturer_code = m.manufacturer_code 6 and manufacturer_code > 'C')6 and manufacturer_code > 'C') 7 order by p.manufacturer_code;7 order by p.manufacturer_code;

PRODUCT_CO PRODUCT_DESCRIPTION MANPRODUCT_CO PRODUCT_DESCRIPTION MAN---------- ----------------------------------- ------------- ----------------------------------- ---XK-S9000 Cassette Deck AIWXK-S9000 Cassette Deck AIWNSX-D2 Mini Component System AIWNSX-D2 Mini Component System AIW310HOB High-output Tower Speakers, Black AR310HOB High-output Tower Speakers, Black AR310HOM High-output Tower Speakers, Maple AR310HOM High-output Tower Speakers, Maple AR310HOC High-output Tower Speakers, Cherry AR310HOC High-output Tower Speakers, Cherry AR266HOB 2-way Tower Speakers, Black AR266HOB 2-way Tower Speakers, Black AR266HOM 2-way Tower Speakers, Maple AR266HOM 2-way Tower Speakers, Maple AR266HOC 2-way Tower Speakers, Cherry AR266HOC 2-way Tower Speakers, Cherry AR ••• •••LS12 Lifestyle 12 Compact Speaker System BOSLS12 Lifestyle 12 Compact Speaker System BOSLS25 Lifestyle 25 Home Theater Speakers BOSLS25 Lifestyle 25 Home Theater Speakers BOSDISC Discount DISDISC Discount DISS/H Shipping and Handling S/HS/H Shipping and Handling S/HCA TAX California Sales Tax TAXCA TAX California Sales Tax TAX

44 rows selected.44 rows selected.

Table Table SubquerySubquery

Not found in Not found in ManufacturersManufacturers

Note. This query can also be accomplished without the subquery.Note. This query can also be accomplished without the subquery.

Creates a subset of rows Creates a subset of rows for all manufacturers with for all manufacturers with code greater than “C”code greater than “C”

Page 43: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

43

R. Ching, Ph.D. • MIS • California State University, Sacramento

SQL> select product_code, product_description, manufacturer_codeSQL> select product_code, product_description, manufacturer_code 2 from products p2 from products p 3 where 3 where not existsnot exists 4 (select * from manufacturers m4 (select * from manufacturers m 5 where p.manufacturer_code = m.manufacturer_code5 where p.manufacturer_code = m.manufacturer_code 6 and manufacturer_code > 'C')6 and manufacturer_code > 'C') 7 order by p.manufacturer_code;7 order by p.manufacturer_code;

PRODUCT_CO PRODUCT_DESCRIPTION MANPRODUCT_CO PRODUCT_DESCRIPTION MAN---------- ----------------------------------- ------------- ----------------------------------- ---XK-S9000 Cassette Deck AIWXK-S9000 Cassette Deck AIWNSX-D2 Mini Component System AIWNSX-D2 Mini Component System AIW310HOB High-output Tower Speakers, Black AR310HOB High-output Tower Speakers, Black AR310HOM High-output Tower Speakers, Maple AR310HOM High-output Tower Speakers, Maple AR310HOC High-output Tower Speakers, Cherry AR310HOC High-output Tower Speakers, Cherry AR266HOB 2-way Tower Speakers, Black AR266HOB 2-way Tower Speakers, Black AR266HOM 2-way Tower Speakers, Maple AR266HOM 2-way Tower Speakers, Maple AR266HOC 2-way Tower Speakers, Cherry AR266HOC 2-way Tower Speakers, Cherry AR ••• •••LS12 Lifestyle 12 Compact Speaker System BOSLS12 Lifestyle 12 Compact Speaker System BOSLS25 Lifestyle 25 Home Theater Speakers BOSLS25 Lifestyle 25 Home Theater Speakers BOSDISC Discount DISDISC Discount DISS/H Shipping and Handling S/HS/H Shipping and Handling S/HCA TAX California Sales Tax TAXCA TAX California Sales Tax TAX

44 rows selected.44 rows selected.

Table Table SubquerySubquery

Not found in Not found in ManufacturersManufacturers

Note. This query can also be accomplished without the subquery.Note. This query can also be accomplished without the subquery.

All All manufacturermanufacturernames > ‘C’names > ‘C’

All All manufacturermanufacturernames > ‘C’names > ‘C’

Exists Exists SetSetNot Exists Not Exists SetSet

All manufacturer names <= ‘C’All manufacturer names <= ‘C’

All rows are drawn from the not exists set

All rows are drawn from the not exists set

Page 44: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

44

R. Ching, Ph.D. • MIS • California State University, Sacramento

SQL> select product_code, product_description, manufacturer_codeSQL> select product_code, product_description, manufacturer_code 2 from products p where 2 from products p where EXISTSEXISTS 3 (select * from manufacturers m3 (select * from manufacturers m 4 where manufacturer_name like 'C%' and4 where manufacturer_name like 'C%' and 5 p.manufacturer_code = m.manufacturer_code)5 p.manufacturer_code = m.manufacturer_code) 6 order by p.manufacturer_code, product_code;6 order by p.manufacturer_code, product_code;

PRODUCT_CO PRODUCT_DESCRIPTION MANPRODUCT_CO PRODUCT_DESCRIPTION MAN---------- ----------------------------------- ------------- ----------------------------------- ---AT-10 Loudspeakers CRVAT-10 Loudspeakers CRVAT-15 Three-way Speaker CRVAT-15 Three-way Speaker CRVSW-12B Subwoofer Speaker System CRVSW-12B Subwoofer Speaker System CRV

Note. This query can also be accomplished without the subquery.Note. This query can also be accomplished without the subquery.

Page 45: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

45

R. Ching, Ph.D. • MIS • California State University, Sacramento

SQL> select product_code, product_description, manufacturer_codeSQL> select product_code, product_description, manufacturer_code 2 from products p where 2 from products p where EXISTSEXISTS 3 (select * from manufacturers m3 (select * from manufacturers m 4 where manufacturer_name like 'C%' and4 where manufacturer_name like 'C%' and 5 5 p.manufacturer_code = m.manufacturer_codep.manufacturer_code = m.manufacturer_code)) 6 order by p.manufacturer_code, product_code;6 order by p.manufacturer_code, product_code;

PRODUCT_CO PRODUCT_DESCRIPTION MANPRODUCT_CO PRODUCT_DESCRIPTION MAN---------- ----------------------------------- ------------- ----------------------------------- ---AT-10 Loudspeakers CRVAT-10 Loudspeakers CRVAT-15 Three-way Speaker CRVAT-15 Three-way Speaker CRVSW-12B Subwoofer Speaker System CRVSW-12B Subwoofer Speaker System CRV

Note. This query can also be accomplished without the subquery.Note. This query can also be accomplished without the subquery.

All All manufacturermanufacturernames like ‘C’names like ‘C’

All All manufacturermanufacturernames like ‘C’names like ‘C’

Exists Exists SetSetNot Exists Not Exists SetSet

All manufacturer names not like ‘C’All manufacturer names not like ‘C’

All rows are drawn from the not exists set

All rows are drawn from the not exists set

Page 46: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

46

R. Ching, Ph.D. • MIS • California State University, Sacramento

SQL> select product_code, product_descriptionSQL> select product_code, product_description 2 from products p2 from products p 3 where 3 where existsexists 4 (select manufacturer_code4 (select manufacturer_code 5 from manufacturers m5 from manufacturers m 6 where manufacturer_name in ('Bose', 'JBL', 'Advent')6 where manufacturer_name in ('Bose', 'JBL', 'Advent') 7 and p.manufacturer_code = m.manufacturer_code);7 and p.manufacturer_code = m.manufacturer_code);

PRODUCT_CO PRODUCT_DESCRIPTIONPRODUCT_CO PRODUCT_DESCRIPTION---------- --------------------------------------------- -----------------------------------VS-100 Center Channel Mini SpeakerVS-100 Center Channel Mini SpeakerPROIIIPLUS Pro III Plus Mini Speaker SystemPROIIIPLUS Pro III Plus Mini Speaker System301-III Direct/Reflecting Speakers301-III Direct/Reflecting Speakers3800 Three-way Speaker System3800 Three-way Speaker System4312 Studio Monitors4312 Studio Monitors901Classic Direct/Reflecting Speaker System901Classic Direct/Reflecting Speaker SystemAM3 Acoustimass Speaker SystemAM3 Acoustimass Speaker SystemAM5 Acoustimass 5 Speaker SystemAM5 Acoustimass 5 Speaker SystemAM7 Acoustimass 7 Speaker SystemAM7 Acoustimass 7 Speaker SystemAM5II Accoustimass-5 Series II SpeakersAM5II Accoustimass-5 Series II Speakers ••• •••301-IV Direct/Reflecting Speakers301-IV Direct/Reflecting Speakers501-V Floor Direct/Reflecting Speakers501-V Floor Direct/Reflecting Speakers701 Tower Speakers701 Tower Speakers

20 rows selected.20 rows selected.

From From scalar scalar exampleexample

Bose, JBL,Bose, JBL,AdventAdvent

Bose, JBL,Bose, JBL,AdventAdvent

Exists Exists SetSet

Not Exists Not Exists SetSet

Page 47: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

47

R. Ching, Ph.D. • MIS • California State University, Sacramento

ANY vs. ALL ExampleANY vs. ALL Example

SQL> SQL> select product_code, product_description,select product_code, product_description, 2 2 product_retail_priceproduct_retail_price 3 3 from products where manufacturer_code = 'PAN';from products where manufacturer_code = 'PAN';

PRODUCT_CO PRODUCT_DESCRIPTION PRODUCT_RETAIL_PRICEPRODUCT_CO PRODUCT_DESCRIPTION PRODUCT_RETAIL_PRICE---------- -------------------------------- ------------------------------ -------------------------------- --------------------CT-27G33 27" 2-Tuner PIP TV 467CT-27G33 27" 2-Tuner PIP TV 467CT-32G23 32" 1-Tuner PIP TV 637CT-32G23 32" 1-Tuner PIP TV 637CT-32G33 32" 2-Tuner PIP TV 722CT-32G33 32" 2-Tuner PIP TV 722CT-32S35 32" Super-flat Tube TV 934CT-32S35 32" Super-flat Tube TV 934DVD-A110 DVD/CD Player 382DVD-A110 DVD/CD Player 382PV-2201 HQ VHS Video Cassette Recorder 206.96PV-2201 HQ VHS Video Cassette Recorder 206.96PV-4210 4-Head VHS Video Cass Recorder 269.96PV-4210 4-Head VHS Video Cass Recorder 269.96PV-4250 HiFi VHS Video Cass Recorder 314.96PV-4250 HiFi VHS Video Cass Recorder 314.96SC-T095 Compact Stereo System 125.96SC-T095 Compact Stereo System 125.96SC-TC430 Compact System w/CD Changer 386.96SC-TC430 Compact System w/CD Changer 386.96

10 rows selected.10 rows selected.

Set of all products whose manufacturer_code = ‘PAN’Set of all products whose manufacturer_code = ‘PAN’

Page 48: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

48

R. Ching, Ph.D. • MIS • California State University, Sacramento

ANY vs. ALL ExampleANY vs. ALL Example

SQL> SQL> select product_code, product_description,select product_code, product_description, 2 2 product_retail_priceproduct_retail_price 3 3 from products where manufacturer_code = 'TEA';from products where manufacturer_code = 'TEA';

PRODUCT_CO PRODUCT_DESCRIPTION PRODUCT_RETAIL_PRICEPRODUCT_CO PRODUCT_DESCRIPTION PRODUCT_RETAIL_PRICE---------- -------------------------------- ------------------------------ -------------------------------- --------------------W-410C Double Cassette Deck 89.96W-410C Double Cassette Deck 89.96W-525R Auto-Reverse Double Cassette 170.96W-525R Auto-Reverse Double Cassette 170.96W-585R Double Cassette Deck W-585R Double Cassette Deck 224.96224.96V-370 Cassette Deck 63.86V-370 Cassette Deck 63.86V-390CHX Cassette Deck 89.96V-390CHX Cassette Deck 89.96EQA-3 Stereo 10-Band Equalizer EQA-3 Stereo 10-Band Equalizer 62.9662.96PD-555 CD Player 116.96PD-555 CD Player 116.96PD-C400 Remote CD Player 152.96PD-C400 Remote CD Player 152.96

8 rows selected.8 rows selected.

Set of all entities (rows) whose manufacturer_code = ‘TEA’Set of all entities (rows) whose manufacturer_code = ‘TEA’

Highest and lowest pricesHighest and lowest prices

Page 49: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

49

R. Ching, Ph.D. • MIS • California State University, Sacramento

ALLALL

SQL> SQL> select product_code, product_retail_priceselect product_code, product_retail_price 2 2 from productsfrom products 3 3 where manufacturer_code = 'PAN' andwhere manufacturer_code = 'PAN' and 4 4 product_retail_price > product_retail_price > ALLALL 5 5 (select product_retail_price from products(select product_retail_price from products 6 6 where manufacturer_code = 'TEA');where manufacturer_code = 'TEA');

PRODUCT_CO PRODUCT_RETAIL_PRICEPRODUCT_CO PRODUCT_RETAIL_PRICE---------- ------------------------------ --------------------CT-27G33 467CT-27G33 467CT-32G23 637CT-32G23 637CT-32G33 722CT-32G33 722CT-32S35 934CT-32S35 934DVD-A110 382DVD-A110 382PV-4210 269.96PV-4210 269.96PV-4250 314.96PV-4250 314.96SC-TC430 386.96SC-TC430 386.96

8 rows selected.8 rows selected.

Returned set of ‘PAN’ products Returned set of ‘PAN’ products with product_retail_price > with product_retail_price > ALLALL ‘TEA’ product_product _price ‘TEA’ product_product _price (i.e., all ‘PAN’ prices exceed (i.e., all ‘PAN’ prices exceed every ‘TEA’ price or the highest every ‘TEA’ price or the highest ‘TEA’price) ‘TEA’price)

Page 50: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

50

R. Ching, Ph.D. • MIS • California State University, Sacramento

ANYANY

SQL> SQL> select product_code, product_retail_priceselect product_code, product_retail_price 2 2 from productsfrom products 3 3 where manufacturer_code = 'PAN' andwhere manufacturer_code = 'PAN' and 4 4 product_retail_price product_retail_price > ANY> ANY 5 5 (select product_retail_price from products(select product_retail_price from products 6 6 where manufacturer_code = 'TEA');where manufacturer_code = 'TEA');

PRODUCT_CO PRODUCT_RETAIL_PRICEPRODUCT_CO PRODUCT_RETAIL_PRICE---------- ------------------------------ --------------------CT-27G33 467CT-27G33 467CT-32G23 637CT-32G23 637CT-32G33 722CT-32G33 722CT-32S35 934CT-32S35 934DVD-A110 382DVD-A110 382PV-2201 206.96PV-2201 206.96PV-4210 269.96PV-4210 269.96PV-4250 314.96PV-4250 314.96SC-T095 125.96SC-T095 125.96SC-TC430 386.96SC-TC430 386.96

10 rows selected.10 rows selected.

Returned set of ‘PAN’ products Returned set of ‘PAN’ products with product_retail_price > with product_retail_price > ANYANY ‘TEA’ product_product _price ‘TEA’ product_product _price (i.e., any ‘PAN’ prices that (i.e., any ‘PAN’ prices that exceeds exceeds aa ‘TEA’ price or the ‘TEA’ price or the lowest ‘TEA’ price) lowest ‘TEA’ price)

Page 51: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

51

R. Ching, Ph.D. • MIS • California State University, Sacramento

ININ

SQL> select product_code "Code", SQL> select product_code "Code", 2 product_description "Product Description",2 product_description "Product Description", 3 to_char(product_retail_price,'$9,999.00') "Price"3 to_char(product_retail_price,'$9,999.00') "Price" 4 from products p4 from products p 5 where p.manufacturer_code 5 where p.manufacturer_code ININ 6 (select m.manufacturer_code6 (select m.manufacturer_code 7 from manufacturers m7 from manufacturers m 8 where upper(manufacturer_name) like '%'||'OS'||'%');8 where upper(manufacturer_name) like '%'||'OS'||'%');

Code Product Description PriceCode Product Description Price---------- ----------------------------------- -------------------- ----------------------------------- ----------VS-100 Center Channel Mini Speaker $116.96VS-100 Center Channel Mini Speaker $116.96301-III Direct/Reflecting Speakers $286.20301-III Direct/Reflecting Speakers $286.20901Classic Direct/Reflecting Speaker System $1,259.90901Classic Direct/Reflecting Speaker System $1,259.90AM3 Acoustimass Speaker System $629.96AM3 Acoustimass Speaker System $629.96AM5 Acoustimass 5 Speaker System $674.96AM5 Acoustimass 5 Speaker System $674.96AM7 Acoustimass 7 Speaker System $809.96AM7 Acoustimass 7 Speaker System $809.96 ......701 Tower Speakers $732.00701 Tower Speakers $732.00

17 rows selected17 rows selected..

Page 52: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

52

R. Ching, Ph.D. • MIS • California State University, Sacramento

ViewsViews

• A dynamic result of one or more relational operations A dynamic result of one or more relational operations operating on the base relations to produce another relation. operating on the base relations to produce another relation. A view is a A view is a virtual relation virtual relation that does not actually exist in that does not actually exist in the database but is produced upon request by a particular the database but is produced upon request by a particular user, at the time of request.user, at the time of request.

• General syntax:General syntax:

CREATE VIEW view-name ASCREATE VIEW view-name ASSELECT ...SELECT ...

Page 53: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

53

R. Ching, Ph.D. • MIS • California State University, Sacramento

Horizontal vs. Vertical ViewsHorizontal vs. Vertical Views

• Horizontal viewHorizontal view– Equivalent to a selectionEquivalent to a selection

create view create view view-nameview-name as as select * from select * from table-name table-name where where conditioncondition

• Vertical viewVertical view– Equivalent to a projection or a projection on a selectionEquivalent to a projection or a projection on a selection

create view create view view-name view-name as as select select column-listcolumn-list from from table-name table-name where where conditioncondition

Page 54: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

54

R. Ching, Ph.D. • MIS • California State University, Sacramento

Creating a ViewCreating a View

Horizontal ViewHorizontal View

SQL> create view Sony_products asSQL> create view Sony_products as 2 (select * from products where manufacturer_code = 'SON');2 (select * from products where manufacturer_code = 'SON');

View created.View created.

Vertical ViewVertical View

SQL> create view economy_priced_products asSQL> create view economy_priced_products as 2 (select product_code, product_description,2 (select product_code, product_description, 3 product_retail_price, retail_unit,3 product_retail_price, retail_unit, 4 manufacturer_code, product_MSRP4 manufacturer_code, product_MSRP 5 from products5 from products 6 where product_retail_price <= 300);6 where product_retail_price <= 300);

View created.View created.

Page 55: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

55

R. Ching, Ph.D. • MIS • California State University, Sacramento

Retrieving from a ViewRetrieving from a View

Creating a join between a view and tableCreating a join between a view and table

SQL> select product_code, manufacturer_name||' - '||SQL> select product_code, manufacturer_name||' - '|| 2 product_description, product_retail_price2 product_description, product_retail_price 3 from economy_priced_products e, manufacturers m3 from economy_priced_products e, manufacturers m 4 where e.manufacturer_code = m.manufacturer_code4 where e.manufacturer_code = m.manufacturer_code 5 and product_retail_price between 250 and 260;5 and product_retail_price between 250 and 260;

CS275 Polk - Center Channel Speaker 254CS275 Polk - Center Channel Speaker 254PD-F907 Pioneer - 100+1 Disc CD Changer 255PD-F907 Pioneer - 100+1 Disc CD Changer 255CS-13RX Mitsubishi - 13" Color TV 251.96CS-13RX Mitsubishi - 13" Color TV 251.96PS-8c Design Acoustics - Point Source Speaker Sytem 251.96PS-8c Design Acoustics - Point Source Speaker Sytem 251.96

Page 56: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

56

R. Ching, Ph.D. • MIS • California State University, Sacramento

Advantages of ViewsAdvantages of Views

• Data independence - external/conceptual mapping Data independence - external/conceptual mapping provides logical independenceprovides logical independence

• CurrencyCurrency

• SecuritySecurity

• Reduced complexityReduced complexity

• ConvenienceConvenience

• CustomizationCustomization

• Data integrityData integrity

Page 57: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

57

R. Ching, Ph.D. • MIS • California State University, Sacramento

Disadvantages of ViewsDisadvantages of Views

• Update restriction - limited to one base tableUpdate restriction - limited to one base table

• Structure restriction - cannot be alteredStructure restriction - cannot be altered

• Performance - can be slowPerformance - can be slow

Page 58: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

58

R. Ching, Ph.D. • MIS • California State University, Sacramento

Updating the DatabaseUpdating the Database

• Modifying the data in the databaseModifying the data in the database

– Insert - Add a new row to a tableInsert - Add a new row to a table

– Update - Modify existing data in a row or rowsUpdate - Modify existing data in a row or rows

– Delete - Remove a row or rows from a tableDelete - Remove a row or rows from a table

Page 59: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

59

R. Ching, Ph.D. • MIS • California State University, Sacramento

INSERTINSERT

• InsertInsert

– Adds a rows into a tableAdds a rows into a table

INSERT INTO table-nameINSERT INTO table-name

(column-name1, ..., column-namen)(column-name1, ..., column-namen)

VALUES (value1, ..., valuen)VALUES (value1, ..., valuen)

Page 60: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

60

R. Ching, Ph.D. • MIS • California State University, Sacramento

SQL> SQL> describe products;describe products; Name Null? TypeName Null? Type ------------------------------- -------- ----------------------------------- -------- ---- PRODUCT_CODE NOT NULL CHAR(10)PRODUCT_CODE NOT NULL CHAR(10) PRODUCT_DESCRIPTION VARCHAR2(35)PRODUCT_DESCRIPTION VARCHAR2(35) PRODUCT_COST NUMBER(8,2)PRODUCT_COST NUMBER(8,2) PRODUCT_MSRP NUMBER(8,2)PRODUCT_MSRP NUMBER(8,2) PRODUCT_RETAIL_PRICE NUMBER(8,2)PRODUCT_RETAIL_PRICE NUMBER(8,2) RETAIL_UNIT CHAR(2)RETAIL_UNIT CHAR(2) MANUFACTURER_CODE CHAR(3)MANUFACTURER_CODE CHAR(3) ACTIVE_DATE DATEACTIVE_DATE DATE NUMBER_ON_HAND NUMBER(6)NUMBER_ON_HAND NUMBER(6) NUMBER_ON_ORDER NUMBER(6)NUMBER_ON_ORDER NUMBER(6) NUMBER_COMMITTED NUMBER(6)NUMBER_COMMITTED NUMBER(6) INACTIVE_DATE DATEINACTIVE_DATE DATE

SQL> SQL> insertinsert into products into products 2 2 (product_code, product_description, (product_code, product_description, 3 3 product_retail_price, retail_unit, active_date)product_retail_price, retail_unit, active_date) 4 4 values ('NEW','New product',599.99,'EA',values ('NEW','New product',599.99,'EA', 5 5 to_date('10-08-99','mm-dd-yy'));to_date('10-08-99','mm-dd-yy'));

1 row created.1 row created. Values MUST correspond to the column names!Values MUST correspond to the column names!

Page 61: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

61

R. Ching, Ph.D. • MIS • California State University, Sacramento

InsertInsert

SQL> SQL> select * from productsselect * from products 2 2 where product_code = 'NEW';where product_code = 'NEW';

PRODUCT_CO PRODUCT_DESCRIPTION PRODUCT_CO PRODUCT_DESCRIPTION PRODUCT_COST PRODUCT_MSRP PRODUCT_RETAIL_PRICE RE MANPRODUCT_COST PRODUCT_MSRP PRODUCT_RETAIL_PRICE RE MAN---------- ----------------------------------- ------------ ---------- ----------------------------------- ------------ ------------ -------------------- -- --------------- -------------------- -- ---ACTIVE_DA NUMBER_ON_HAND NUMBER_ON_ORDER NUMBER_COMMITTED ACTIVE_DA NUMBER_ON_HAND NUMBER_ON_ORDER NUMBER_COMMITTED INACTIVE_INACTIVE_--------- -------------- --------------- ---------------- --------- -------------- --------------- ---------------- ------------------NEW New product NEW New product 599.99 EA599.99 EA08-OCT-99 0 0 008-OCT-99 0 0 0

All columns that are not assigned a value by the INSERT are All columns that are not assigned a value by the INSERT are assigned null values UNLESS a default value was specified assigned null values UNLESS a default value was specified when the table was created.when the table was created.

All columns that are not assigned a value by the INSERT are All columns that are not assigned a value by the INSERT are assigned null values UNLESS a default value was specified assigned null values UNLESS a default value was specified when the table was created.when the table was created.

Page 62: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

62

R. Ching, Ph.D. • MIS • California State University, Sacramento

UPDATEUPDATE

• UpdateUpdate

– Modifies column values in the tableModifies column values in the table

UPDATE table-nameUPDATE table-nameSET column-name = {expression | literal}SET column-name = {expression | literal}[WHERE condition][WHERE condition]

Page 63: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

63

R. Ching, Ph.D. • MIS • California State University, Sacramento

SQL> SQL> update productsupdate products 2 2 set number_on_hand = 25set number_on_hand = 25 3 3 where product_code = 'NEW';where product_code = 'NEW';

1 row updated.1 row updated.

SQL> select product_code, number_on_handSQL> select product_code, number_on_hand 2 from products where product_code = 'NEW';2 from products where product_code = 'NEW';

PRODUCT_CO NUMBER_ON_HANDPRODUCT_CO NUMBER_ON_HAND---------- ------------------------ --------------NEW 25NEW 25

Updating a Single RowUpdating a Single Row

Page 64: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

64

R. Ching, Ph.D. • MIS • California State University, Sacramento

Updating Multiple Rows Updating Multiple Rows Using a Recursive Arithmetic OperationUsing a Recursive Arithmetic Operation

SQL> SQL> update productsupdate products 2 2 set product_retail_price = product_retail_price * 1.1set product_retail_price = product_retail_price * 1.1 3 3 where manufacturer_code = 'BOS';where manufacturer_code = 'BOS';

17 rows updated.17 rows updated.

Product retail prices for all Bose (BOS) products are increased Product retail prices for all Bose (BOS) products are increased by 10 percent.by 10 percent.Product retail prices for all Bose (BOS) products are increased Product retail prices for all Bose (BOS) products are increased by 10 percent.by 10 percent.

Page 65: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

65

R. Ching, Ph.D. • MIS • California State University, Sacramento

Deleting a TableDeleting a Table

SQL> SQL> delete products;delete products;

319 rows deleted.319 rows deleted.

SQL> SQL> rollback;rollback;

Rollback complete.Rollback complete.

SQL> select count(*) from products;SQL> select count(*) from products;

COUNT(*)COUNT(*)------------------ 319319

• Delete (not be confused with Drop)Delete (not be confused with Drop)– Delete rows from a tableDelete rows from a table

DELETE DELETE table-nametable-name

Rollback Rollback returns the database to its returns the database to its previous committed state.previous committed state.Rollback Rollback returns the database to its returns the database to its previous committed state.previous committed state.

Page 66: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

66

R. Ching, Ph.D. • MIS • California State University, Sacramento

Deleting a Row from a TableDeleting a Row from a Table

DELETE DELETE table-nametable-name

WHERE WHERE conditioncondition

SQL> SQL> delete productsdelete products 2 2 where product_code = 'NEW';where product_code = 'NEW';

1 row deleted.1 row deleted.

SQL> SQL> commit;commit;

Commit complete.Commit complete.

Commit permanently commits all Commit permanently commits all changes (i.e., inserts, updates, deletes) to changes (i.e., inserts, updates, deletes) to the database.the database.

Commit permanently commits all Commit permanently commits all changes (i.e., inserts, updates, deletes) to changes (i.e., inserts, updates, deletes) to the database.the database.

Page 67: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

67

R. Ching, Ph.D. • MIS • California State University, Sacramento

Et cetera:Et cetera: Changing Column Titles Changing Column TitlesUsing a Column AliasUsing a Column Alias

SQL> SQL> select po_number select po_number as "PO"as "PO",, 2 2 to_char(po_date,'fmMonth dd, yyyy') to_char(po_date,'fmMonth dd, yyyy') as "PO Date"as "PO Date",, 3 3 to_char(total_amount,'999,990.00') to_char(total_amount,'999,990.00') as "Total Amount"as "Total Amount" 4 4 from purchase_ordersfrom purchase_orders 5 5 where po_date > (sysdate - 45);where po_date > (sysdate - 45);

PO PO Date Total AmounPO PO Date Total Amoun----- ------------------ ---------------- ------------------ -----------10018 September 11, 1999 36,189.0510018 September 11, 1999 36,189.0510019 September 18, 1999 5,394.4010019 September 18, 1999 5,394.4010020 September 25, 1999 15,313.6510020 September 25, 1999 15,313.6510021 October 2, 1999 25,470.1510021 October 2, 1999 25,470.1510022 October 9, 1999 1,949.7010022 October 9, 1999 1,949.70

Page 68: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

68

R. Ching, Ph.D. • MIS • California State University, Sacramento

Embedded SQLEmbedded SQL

• For programming languages (3GL, 4GL)For programming languages (3GL, 4GL)• SQL statements encapsulated in EXECsSQL statements encapsulated in EXECs

EXEC SQLEXEC SQLSQL commandSQL command

END EXECEND EXEC• Three sections (in most cases)Three sections (in most cases)

– Host variables - retains values passed to and from the Host variables - retains values passed to and from the columns of a tablecolumns of a table

– SQLCA (communications area) - retains codes and SQLCA (communications area) - retains codes and messages sent between the application and DBMSmessages sent between the application and DBMS

– Processing (e.g., procedure division in COBOL)Processing (e.g., procedure division in COBOL)

Page 69: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

69

R. Ching, Ph.D. • MIS • California State University, Sacramento

Host VariablesHost Variables

* Declare Host Variables* Declare Host Variables** EXEC SQL BEGIN DECLARE SECTION END-EXEC.EXEC SQL BEGIN DECLARE SECTION END-EXEC.** 01 USERNAME PIC X(20) VALUE "mis108".01 USERNAME PIC X(20) VALUE "mis108". 01 PASSWORD PIC X(20) VALUE "mis108".01 PASSWORD PIC X(20) VALUE "mis108". 01 PRODUCT-CODE PIC X(10).01 PRODUCT-CODE PIC X(10). 01 PRODUCT-DESCRIPTION PIC X(35).01 PRODUCT-DESCRIPTION PIC X(35). 01 RETAIL-PRICE COMP-1. 01 RETAIL-PRICE COMP-1. 01 MSRP COMP-1.01 MSRP COMP-1. 01 COST COMP-1.01 COST COMP-1. 01 RETAIL-UNIT PIC X(02).01 RETAIL-UNIT PIC X(02). 01 NUMBER-ON-HAND PIC S9(09) COMP-5.01 NUMBER-ON-HAND PIC S9(09) COMP-5. 01 MANUFACTURER-CODE PIC X(03).01 MANUFACTURER-CODE PIC X(03). 01 MANUFACTURER-NAME PIC X(30).01 MANUFACTURER-NAME PIC X(30).**

In COBOLIn COBOL

Page 70: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

70

R. Ching, Ph.D. • MIS • California State University, Sacramento

SQLCA (Inserted by Precompiler)SQLCA (Inserted by Precompiler)

* EXEC SQL INCLUDE SQLCA END-EXEC.* EXEC SQL INCLUDE SQLCA END-EXEC.*** * * $Header: sqlca.cob 7010200.1 93/11/30 13:59:57 snataraj >* $Header: sqlca.cob 7010200.1 93/11/30 13:59:57 snataraj >* * *********************************************************************************************************************************** ** ** S Q L C A ** S Q L C A ** (This file in ANSI format. Do NOT bse it). ** (This file in ANSI format. Do NOT bse it). ** ** ** MODIFIED ** MODIFIED ** Clare 12/06/84 - Ch SQLCA to not be an EXTERNAL. ** Clare 12/06/84 - Ch SQLCA to not be an EXTERNAL. *********************************************************************************************************************************** 01 SQLCA.01 SQLCA. 05 SQLCAID PIC X(8).05 SQLCAID PIC X(8). 05 SQLCABC PIC S9(9) COMP-5.05 SQLCABC PIC S9(9) COMP-5. 05 SQLCODE PIC S9(9) COMP-5.05 SQLCODE PIC S9(9) COMP-5. 05 SQLERRM.05 SQLERRM. 49 SQLERRML PIC S9(4) COMP-5.49 SQLERRML PIC S9(4) COMP-5. 49 SQLERRMC PIC X(70).49 SQLERRMC PIC X(70).

Page 71: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

71

R. Ching, Ph.D. • MIS • California State University, Sacramento

SQLCASQLCA

05 SQLERRP PIC X(8). 05 SQLERRP PIC X(8). 05 SQLERRD OCCURS 6 TIMES05 SQLERRD OCCURS 6 TIMES PIC S9(9) COMP-5.PIC S9(9) COMP-5. 05 SQLWARN. 05 SQLWARN. 10 SQLWARN0 PIC X(1). 10 SQLWARN0 PIC X(1). 10 SQLWARN1 PIC X(1).10 SQLWARN1 PIC X(1). 10 SQLWARN2 PIC X(1).10 SQLWARN2 PIC X(1). 10 SQLWARN3 PIC X(1).10 SQLWARN3 PIC X(1). 10 SQLWARN4 PIC X(1).10 SQLWARN4 PIC X(1). 10 SQLWARN5 PIC X(1).10 SQLWARN5 PIC X(1). 10 SQLWARN6 PIC X(1).10 SQLWARN6 PIC X(1). 10 SQLWARN7 PIC X(1).10 SQLWARN7 PIC X(1). 05 SQLEXT PIC X(8).05 SQLEXT PIC X(8).

Cont.Cont.

Page 72: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

72

R. Ching, Ph.D. • MIS • California State University, Sacramento

Embedded SQLEmbedded SQL

EXEC SQLEXEC SQL SELECT MANUFACTURER_NAMESELECT MANUFACTURER_NAME INTO :MANUFACTURER-NAMEINTO :MANUFACTURER-NAME FROM MANUFACTURERSFROM MANUFACTURERS WHERE MANUFACTURER_CODE =WHERE MANUFACTURER_CODE = (SELECT MANUFACTURER_CODE(SELECT MANUFACTURER_CODE FROM PRODUCTSFROM PRODUCTS WHERE PRODUCT_CODE = :PRODUCT-CODE)WHERE PRODUCT_CODE = :PRODUCT-CODE)END-EXEC.END-EXEC.

Note. Host variables are preceded by colon (:)Note. Host variables are preceded by colon (:)

Host variablesHost variables

Page 73: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

73

R. Ching, Ph.D. • MIS • California State University, Sacramento

EXEC SQLEXEC SQL DECLARE PCURSOR CURSOR FORDECLARE PCURSOR CURSOR FOR SELECT PRODUCT_CODE, PRODUCT_DESCRIPTION,SELECT PRODUCT_CODE, PRODUCT_DESCRIPTION, PRODUCT_RETAIL_PRICE, RETAIL_UNIT,PRODUCT_RETAIL_PRICE, RETAIL_UNIT, NUMBER_ON_HANDNUMBER_ON_HAND FROM PRODUCTSFROM PRODUCTS * WHERE MANUFACTURER_CODE = 'SON'* WHERE MANUFACTURER_CODE = 'SON' END-EXEC.END-EXEC. ** EXEC SQLEXEC SQL OPEN PCURSOROPEN PCURSOR END-EXEC.END-EXEC. ** PERFORM 1000-RETRIEVE-ROWSPERFORM 1000-RETRIEVE-ROWS UNTIL SQLCODE NOT = 0.UNTIL SQLCODE NOT = 0. ** EXEC SQLEXEC SQL CLOSE PCURSORCLOSE PCURSOR END-EXEC.END-EXEC.

Sequentially Retrieving RowsSequentially Retrieving Rows

Defines Defines a a cursorcursor

Places the cursor at the beginning Places the cursor at the beginning row of the SELECTrow of the SELECT

Closes the cursorCloses the cursor

Page 74: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

74

R. Ching, Ph.D. • MIS • California State University, Sacramento

1000-RETRIEVE-ROWS.1000-RETRIEVE-ROWS. ** EXEC SQLEXEC SQL FETCH PCURSORFETCH PCURSOR INTO :PRODUCT-CODE, :PRODUCT-DESCRIPTION,INTO :PRODUCT-CODE, :PRODUCT-DESCRIPTION, :RETAIL-PRICE, :RETAIL-UNIT, :RETAIL-PRICE, :RETAIL-UNIT, :NUMBER-ON-HAND:NUMBER-ON-HAND END-EXEC.END-EXEC. ** IF SQLCODE = 0IF SQLCODE = 0 DISPLAY PRODUCT-CODE "."DISPLAY PRODUCT-CODE "."

Sequentially retrieves rows from the table based upon Sequentially retrieves rows from the table based upon the SELECT defined in the DECLARE CURSORthe SELECT defined in the DECLARE CURSOR

Page 75: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

75

R. Ching, Ph.D. • MIS • California State University, Sacramento

* EXEC SQL* EXEC SQL * DECLARE PCURSOR CURSOR FOR* DECLARE PCURSOR CURSOR FOR * SELECT PRODUCT_CODE, PRODUCT_DESCRIPTION,* SELECT PRODUCT_CODE, PRODUCT_DESCRIPTION, * PRODUCT_RETAIL_PRICE, RETAIL_UNIT,* PRODUCT_RETAIL_PRICE, RETAIL_UNIT, * NUMBER_ON_HAND* NUMBER_ON_HAND * FROM PRODUCTS* FROM PRODUCTS * WHERE MANUFACTURER_CODE = 'SON'* WHERE MANUFACTURER_CODE = 'SON' * END-EXEC.* END-EXEC. ** * EXEC SQL* EXEC SQL * OPEN PCURSOR* OPEN PCURSOR * END-EXEC.* END-EXEC. ** CALL "_SQLADR" USING SQ0001 SQL-STMTCALL "_SQLADR" USING SQ0001 SQL-STMT MOVE 1 TO SQL-ITERSMOVE 1 TO SQL-ITERS MOVE 36 TO SQL-OFFSETMOVE 36 TO SQL-OFFSET CALL "_SQLADR" USINGCALL "_SQLADR" USING SQLCUDSQLCUD SQL-CUDSQL-CUD CALL "_SQLADR" USINGCALL "_SQLADR" USING SQLCASQLCA SQL-SQLESTSQL-SQLEST MOVE 0 TO SQL-SQLETYMOVE 0 TO SQL-SQLETY

CALL "_SQLBEX" USINGCALL "_SQLBEX" USING SQLCTXSQLCTX SQLEXDSQLEXD SQLFPNSQLFPN ..

After precompiling the After precompiling the COBOL programCOBOL program

Page 76: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

76

R. Ching, Ph.D. • MIS • California State University, Sacramento

* EXEC SQL* EXEC SQL * FETCH PCURSOR* FETCH PCURSOR * INTO :PRODUCT-CODE, :PRODUCT-DESCRIPTION,* INTO :PRODUCT-CODE, :PRODUCT-DESCRIPTION, * :RETAIL-PRICE, :RETAIL-UNIT, :NUMBER-ON-HAND* :RETAIL-PRICE, :RETAIL-UNIT, :NUMBER-ON-HAND * END-EXEC.* END-EXEC. ** MOVE 1 TO SQL-ITERSMOVE 1 TO SQL-ITERS MOVE 80 TO SQL-OFFSETMOVE 80 TO SQL-OFFSET CALL "_SQLADR" USINGCALL "_SQLADR" USING SQLCUDSQLCUD SQL-CUDSQL-CUD CALL "_SQLADR" USINGCALL "_SQLADR" USING SQLCASQLCA SQL-SQLESTSQL-SQLEST MOVE 0 TO SQL-SQLETYMOVE 0 TO SQL-SQLETY CALL "_SQLADR" USINGCALL "_SQLADR" USING PRODUCT-CODEPRODUCT-CODE SQL-SQHSTV(1)SQL-SQHSTV(1) MOVE 10 TO SQL-SQHSTL(1)MOVE 10 TO SQL-SQHSTL(1) MOVE 0 TO SQL-SQINDV(1)MOVE 0 TO SQL-SQINDV(1) MOVE 0 TO SQL-SQHARM(1)MOVE 0 TO SQL-SQHARM(1) CALL "_SQLADR" USINGCALL "_SQLADR" USING PRODUCT-DESCRIPTIONPRODUCT-DESCRIPTION SQL-SQHSTV(2)SQL-SQHSTV(2) MOVE 35 TO SQL-SQHSTL(2)MOVE 35 TO SQL-SQHSTL(2) MOVE 0 TO SQL-SQINDV(2)MOVE 0 TO SQL-SQINDV(2) MOVE 0 TO SQL-SQHARM(2)MOVE 0 TO SQL-SQHARM(2) CALL "_SQLADR" USINGCALL "_SQLADR" USING RETAIL-PRICERETAIL-PRICE SQL-SQHSTV(3)SQL-SQHSTV(3) MOVE 3 TO SQL-SQHSTL(3)MOVE 3 TO SQL-SQHSTL(3) MOVE 0 TO SQL-SQINDV(3)MOVE 0 TO SQL-SQINDV(3) MOVE 0 TO SQL-SQHARM(3)MOVE 0 TO SQL-SQHARM(3) CALL "_SQLADR" USINGCALL "_SQLADR" USING RETAIL-UNITRETAIL-UNIT SQL-SQHSTV(4)SQL-SQHSTV(4) MOVE 2 TO SQL-SQHSTL(4)MOVE 2 TO SQL-SQHSTL(4) MOVE 0 TO SQL-SQINDV(4)MOVE 0 TO SQL-SQINDV(4) MOVE 0 TO SQL-SQHARM(4)MOVE 0 TO SQL-SQHARM(4) CALL "_SQLADR" USINGCALL "_SQLADR" USING NUMBER-ON-HANDNUMBER-ON-HAND SQL-SQHSTV(5)SQL-SQHSTV(5) MOVE 4 TO SQL-SQHSTL(5)MOVE 4 TO SQL-SQHSTL(5) MOVE 0 TO SQL-SQINDV(5)MOVE 0 TO SQL-SQINDV(5) MOVE 0 TO SQL-SQHARM(5)MOVE 0 TO SQL-SQHARM(5) CALL "_SQLADR" USINGCALL "_SQLADR" USING SQL-SQHSTV(1)SQL-SQHSTV(1) SQL-SQPHSVSQL-SQPHSV CALL "_SQLADR" USINGCALL "_SQLADR" USING SQL-SQHSTL(1)SQL-SQHSTL(1) SQL-SQPHSLSQL-SQPHSL CALL "_SQLADR" USINGCALL "_SQLADR" USING SQL-SQINDV(1)SQL-SQINDV(1) SQL-SQPINDSQL-SQPIND CALL "_SQLADR" USINGCALL "_SQLADR" USING SQL-SQHARM(1)SQL-SQHARM(1) SQL-SQPARMSQL-SQPARM CALL "_SQLADR" USINGCALL "_SQLADR" USING SQL-SQHARC(1)SQL-SQHARC(1) SQL-SQPARCSQL-SQPARC

CALL "_SQLBEX" USINGCALL "_SQLBEX" USING SQLCTXSQLCTX SQLEXDSQLEXD SQLFPNSQLFPN ..

Precompiler (Oracle’s Pro*COBOL) Precompiler (Oracle’s Pro*COBOL) converts SQL to COBOL codeconverts SQL to COBOL code

SQLSQL

Page 77: 1 R. Ching, Ph.D. MIS California State University, Sacramento Week 6 October 3 SQL: Joins, Set Operations, Aggregation Functions, Subqueries ANY/ALL and.

77

R. Ching, Ph.D. • MIS • California State University, Sacramento