INFS1603 Lab Manual (v1.11)

download INFS1603 Lab Manual (v1.11)

of 146

Transcript of INFS1603 Lab Manual (v1.11)

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    1/146

    Australian School of BusinessSchool of Information Systems, Technology and Management

    ORACLE LAB MANUAL

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    2/146

    ii

    UNSW

    SISTM

    Lab Manual

    Document Update:

    Author Date SQL Developer Version Version

    Vincent Pang Feb, 2011 2.1.1.64 v1.00Vincent Pang Dec, 2011 3.0.04 v1.11

    References:

    The following referencing materials were used to create this Oracle Lab Manual:

    (1) Casteel, Joan, Oracle 11g: SQL, 2010, Cengage Learning(2) Oracle Database: SQL Fundamentals I, Oracle Education(3) Oracle Database: SQL Fundamentals II, Oracle Education(4) Oracle SQL Developer 2.1 Users Guide, Oracle(5) Http://www.oracle.com(6) Date, C. J., 1995, An Introduction to Database Systems, 6th Edition,

    Addison-Wesley Publishing, USA.

    File Name:

    UNSW SISTM Oracle Lab Manual v1.11

    Copyright:

    This Oracle Lab Manual is created for the Information Systems courses, offered by

    the School of Information Systems, Technology and Management, the University

    of New South Wales, Sydney, Australia.

    http://www.oracle.com/http://www.oracle.com/http://www.oracle.com/
  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    3/146

    iii

    UNSW

    SISTM

    LabManual

    Table of Contents

    Table of Contents ......................................... ................................................................. ............................ iii

    Table of Figures ....................................................... ................................................................. ............... viii

    Table of Tables ........................................................ ................................................................. ................ xiiIntroduction to Oracle and Relational Database ........................................................ ........................... 13

    History of Oracle ................................................................................................................................... 13History of SQL ...................................................................................................................................... 13SQL Standards ...................................................... ................................................................. ................ 13Oracle 11g............................................................................................................................................. 14Information Systems Courses ................................................................................................ ................ 15Data Modelling ..................................................... ................................................................. ................ 15Relational Database ......................................................... ................................................................. ..... 16A Table .................................................................................................................................................. 16Oracle SQL Statements.......................................................................................................................... 17Lab/Tutorial Arrangement ............................................................................................................. ........ 18

    Introduction to Oracle SQL Developer ............................................................ ...................................... 19

    SQL Developer Layout and Functionality ....................................................... ...................................... 20Connecting to a Database ...................................................................................................................... 21

    Instructions to Connect to a Database ......................................................... ...................................... 21Reference ......................................................... ................................................................. ................ 22Open a Database ......................................................... ................................................................. ..... 22

    Executing SQL Statements in Oracle SQL Developer .................................................................. ........ 23Summary ............................................................... ................................................................. ................ 24

    Lab Week 2 Basic SQL SELECT statements ....................................................................................... 252.1 Objectives ....................................................... ................................................................. ................ 25

    2.1.1 Reference ........................................................... ................................................................. ..... 252.1.2 Database .................................................................................................................................. 25

    2.2 SELECT Statement ............................................................... ........................................................... 252.2.1 Selecting All Data from a Table .............................................................................. ................ 25

    2.2.1.1 Example: Selecting All Data from a Table ....................................................................... 252.3 Selecting a Column or Columns from a Table ................................................................ ................. 26

    2.3.1.1 Example: Selecting One Column Only ............................................................. ................ 262.3.1.2 Example: Selecting More Than One Column .............................................................. ..... 26

    2.3.2 Viewing Table Structure ......................................................... ................................................. 272.3.2.1 Example: Find the Column Names of a Table .................................................................. 27

    2.3.3 Null Values ........................................................ ................................................................. ..... 27Difference between CHAR(n) and VARCHAR2(n)........................................................................... 28

    2.4 SELECT Statement ......................................................................................... ..... 292.4.1.1 Example: -- Demonstrate Four Common Alias Methods.......................................... ........ 29

    2.5 SELECT DISTINCT Statement....................................................................................................... 302.5.1.1 Example: Using Distinct ............................................................. ...................................... 30

    2.5.2 Use DISTINCT for Two or More Columns ............................................................. ................ 312.6 SELECT and Statement .......................................................... 32

    2.6.1.1 Example: Using Concatenation and Literal Strings .......................................................... 322.6.1.2 Example: Single Quotation Mark ............................................................................. ........ 33

    2.7 Arithmetic Operations ..................................................................................................................... 342.7.1.1 Example: Arithmetic Operation ............................................................. ........................... 34

    Lab Week 3 Restricting Rows and Sorting Data ....................................................... ........................... 353.1 Objectives ....................................................... ................................................................. ................ 35

    3.1.1 Reference ........................................................... ................................................................. ..... 353.1.2 Database .................................................................................................................................. 35

    3.2 SELECT Statement ................................................................ ........................... 353.2.1 Numeric, Character Strings and Dates .......................................................... ........................... 35

    3.2.1.1 Example: Numeric Values .......................................................... ...................................... 35

    3.2.1.2 Example: Character Strings ........................................................ ...................................... 363.2.1.3 Example: Date Values ...................................................................................................... 363.3 Logical Operators ............................................................................................................................ 37

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    4/146

    iv

    UNSW

    SISTM

    Lab Manual

    3.4 Comparison Operators .................................................................................................. ................... 383.4.1.1 Example: Condition based on Numeric Value ............................................................. ..... 393.4.1.2 Example: Condition based on Character Strings ......................................................... ..... 413.4.1.3 Example: Condition based on a Date Values ............................................................... ..... 443.4.1.4 Example: The use of Not Equal or NOT Operator ........................................................... 44

    3.4.1.5 Example: The use of LIKE Operator ................................................................................ 463.4.2 Rules of Precedence ................................................................ ................................................. 48

    3.5 SELECT Statement .......................... ........................................................... 483.5.1.1 Example: Sort by Numeric and Date Values ............................................................... ..... 49

    3.5.2 Sort NULL Values ........................................................ ........................................................... 50

    Lab Week 4 Selected Single-Row Functions .............................................................. ........................... 514.1 Objectives ....................................................... ................................................................. ................ 51

    4.1.1 Reference ........................................................... ................................................................. ..... 514.1.2 Database .................................................................................................................................. 51

    4.2 Overview of Functions .................................................................................................................... 514.2.1 Case Conversion Functions ..................................................................................................... 51

    4.2.1.1 Example: Case Conversion Function ................................................................................ 524.3 Character Manipulation Functions ............................................................. ...................................... 52

    4.3.1.1 Example: Character Manipulation Functions .................. ................................................. 534.4 Number Functions ........................................................................................................................... 53

    4.4.1.1 Example: Examples of using Number Functions ......................................................... ..... 544.4.2 The Dual Table ........................................................................................................................ 54

    4.5 Date Functions ................................................................................................................. ................ 554.5.1.1 Example: Date Function ................................................................................................... 55

    4.6 Regular Expressions ........................................................................................................................ 554.7 Other Functions ............................................................................................................................... 56

    4.7.1.1 Example: Using NVL Functions ............................................................ ........................... 574.8 CASE Expression ............................................................................................................................ 59

    Lab Week 5 Joining Data from Multiple Tables ....................................................... ........................... 615.1 Objectives ....................................................... ................................................................. ................ 61

    5.1.1 Reference ........................................................... ................................................................. ..... 615.1.2 Database .................................................................................................................................. 61

    5.2 Relational Algebra ........................................................................................................... ................ 615.3 Purpose of Joins ......................................................... ................................................................. ..... 65

    5.3.1 Cartesian Joins .............................................................. ........................................................... 655.4 Using Alias for Tables .......................................................... ........................................................... 665.5 Traditional Join Method versus ANSI JOIN Method ...................................................................... 675.6 Equality Joins .................................................................................................................................. 68

    5.6.1 NATURAL JOIN Clause ........................................................ ................................................. 685.6.1.1 Example: Using NATURAL JOIN ........................................................ ........................... 68

    5.6.2 JOIN USING Clause.......................................................... ................................................. 705.6.2.1 Example: JOIN USING Clause with Alias.................................................................. 71

    5.6.3 JOIN ON Clause................................................................ ................................................. 715.6.3.1 Example: JOIN ON Clause............................................................... ........................... 71

    5.7 Non-equality Joins ........................................................................................................... ................ 735.8 Self-Joins ......................................................................................................................................... 74

    5.8.1.1 Example: Self-Joins .......................................................................................................... 745.8.2 INNER JOINS .............................................................................................. ........................... 74

    5.9 OUTER JOINS ................................................................................................................ ................ 745.9.1 Difference between INNER and OUTER Joins ................................................................ ....... 745.9.2 LEFT OUTER JOIN ................................................................ ................................................ 75

    5.9.2.1 Example: Using LEFT OUTER JOINS ............................................................ ................ 755.9.3 RIGHT OUTER JOIN .................................................................................. ........................... 76

    5.9.3.1 Example: RIGHT OUTER JOIN ...................................................................................... 765.9.4 FULL JOIN.............................................................................................................................. 76

    5.10 SET OPERATORS ............................................................. ........................................................... 775.10.1 UNION ....................................................................................................... ........................... 77

    5.10.1.1 Example: UNION ........................................................................................... ................ 775.10.2 UNION ALL.......................................................................................................................... 78

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    5/146

    v

    UNSW

    SISTM

    LabManual

    5.10.3 INTERSECT ............................................................... ........................................................... 785.10.4 MINUS .................................................................................................................................. 80

    Lab Week 6 Group Functions ................................................................ ................................................ 816.1 Objectives ....................................................... ................................................................. ................ 81

    6.1.1 Reference ........................................................... ................................................................. ..... 81

    6.1.2 Database .................................................................................................................................. 816.2 Understand Grouping ............................................................ ........................................................... 816.3 SELECT Statement ................................................... ................................................. 84

    6.3.1 Group Functions ...................................................................................................................... 846.3.1.1 Example: Group Functions ............................................................................... ................ 84

    6.3.2 Other Data Types .......................................................... ........................................................... 856.3.2.1 Example: Date Values ...................................................................................................... 85

    6.3.3 COUNT ................................................................................................................................... 856.3.3.1 Example: Using COUNT .................................................................................................. 856.3.3.2 Example: Handling NULL Values ......................................................... ........................... 86

    6.3.4 Grouping Data ......................................................................................................................... 876.3.4.1 Example: GROUP BY ........................................................................... ........................... 876.3.4.2 Example: GROUP BY, ORDER BY, WHERE and HAVING ......................................... 88

    6.3.4.3 Example: Complex Queries ................................................................... ........................... 89Lab Week 7 Table Creation, Constraints and Management .......................................................... ..... 91

    7.1 Objectives ....................................................... ................................................................. ................ 917.1.1 Reference ........................................................... ................................................................. ..... 91

    7.2 CREATE TABLE Statement ................................................................................................... ........ 917.2.1.1 Example: CREATE a TABLE .............................................................. ........................... 92

    7.2.2 User Tables ........................................................ ................................................................. ..... 937.3 CREATE TABLE AS Statement........................................................................................... 93

    7.3.1.1 Example: CREATE TABLE AS ............................................................. ................ 937.4 Modifying An Existing Table ......................................................... ................................................. 94

    7.4.1.1 Example: ALTER TABLEAdd, Modify and Drop ....................................................... 947.5 ALTER TABLESET UNUSED (and DROP) Statement............................................................. 95

    7.5.1.1 Example: ALTER TABLE SET UNUNSED and DROP............................................ 967.6 Renaming a Table ....................................................................................................................... ..... 967.7 Truncating a Table ................................................................ ........................................................... 977.8 Deleting a Table ......................................................... ................................................................. ..... 977.9 Constraints ...................................................... ................................................................. ................ 98

    7.9.1 Create Constraints ......................................................... ........................................................... 997.9.2 Create a Table with Constraints ......................................................... .................................... 100

    7.9.2.1 Example: Primary and Foreign Keys in the Statement ................................................... 1007.9.3 Composite Primary Key ........................................................................................................ 1017.9.4 Using the UNIQUE Constraint .............................................................................................. 101

    7.9.4.1 Example: Unique Key Violation ............................................................ ......................... 1027.10 Using the NOT NULL Constraint ............................................................................................... 1027.11 CHECK Constraint ................................................................................................................ ...... 1037.12 Drop Constraints ................................................................ .......................................................... 103

    7.12.1.1 Example: Dropping a Primary Key and Constraints ..................................................... 1047.13 Enable and Disable Constraints ..................................................................................... .............. 104

    Lab Week 8 Data Manipulation Language (DML) and Transaction Control ................................. 1058.1 Objectives ....................................................... ................................................................. .............. 105

    8.1.1 Reference ........................................................... ................................................................. ... 1058.1.2 Database ................................................................................................................................ 105

    8.2 Data Manipulation Language (DML) Commands ......................................................................... 1058.2.1 INSERT Command ................................................................. ............................................... 105

    8.2.1.1 Example: Insert a New Row ........................................................................................... 1068.2.1.2 Example: Primary Key Constraint Violation ............................................................... ... 1078.2.1.3 Example: Foreign Key Constraint Violation .................................................... .............. 1098.2.1.4 Example: Initialised with Default Values ................................................................. ...... 109

    8.2.2 INSERTING Data from an Existing Table .............................................................. .............. 1108.2.2.1 Example: Inserting Data from an Existing Table ......................................................... ... 1108.2.3 UPDATE Command ................................................................ .............................................. 111

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    6/146

    vi

    UNSW

    SISTM

    Lab Manual

    8.2.4 Substitution Variables .............................................................. .............................................. 1128.2.4.1 Example: Using Substitution Variables .......................................................................... 112

    8.2.5 DELETE Command............................................................................................................... 1148.3 Transaction Control Commands ................................................................................................ .... 115

    8.3.1 COMMIT Command ............................................................................................... .............. 115

    8.3.2 ROLLBACK Command ........................................................................................................ 1158.4 SAVEPOINT and ROLLBACK TO Commands ............................................................. .............. 115

    8.4.1.1 Example: Savepoint and Rollback ......................................................... ......................... 1168.5 Next Sequence Number ........................................................................................ ......................... 1178.6 Table Locks ................................................................................................................................... 118

    8.6.1 LOCK TABLE Command Shared Lock ....................................................... ......................... 1188.6.2 LOCK TABLE Command Exclusive Lock .................................................. ......................... 118

    8.7 SELECTFOR UPDATE Command....................................................... .................................... 118

    Lab Week 9 Subqueries and Merge Statements ........................................................ ......................... 1199.1 Objectives ....................................................... ................................................................. .............. 119

    9.1.1 Reference ........................................................... ................................................................. ... 1199.1.2 Database ................................................................................................................................ 119

    9.2 Subqueries and Their Uses ............................................................................................................ 119

    9.2.1 Single-Row Subquery ............................................................................................................ 1209.2.1.1 Example: Single-Row Subquery in a WHERE Clause ................................................... 1209.2.1.2 Example: Single-Row Subquery in a HAVING Clause.................................................. 1219.2.1.3 Example: Single-Row Subquery in a SELECT Clause ................................................... 121

    9.3 Multiple-Row Subqueries .............................................................................................................. 1229.3.1.1 Example: Using the IN Operator ................................................................... ................. 1229.3.1.2 Example: Using the ALL Operator ........................................................ ......................... 1239.3.1.3 Example: Using the ANY Operator ....................................................... ......................... 124

    9.4 Multiple-Column Subqueries .......................................................... ............................................... 1259.4.1 Multiple-Column Subquery in a FROM clause ................................................................ ..... 1259.4.2 Multiple-Column Subquery in a WHERE clause .................................................................. 126

    9.5 Nested Subqueries ......................................................................................................................... 1279.6 Correlated Subqueries ........................................................... ......................................................... 127

    9.6.1.1 Example: Correlated Subqueries ............................................................ ......................... 1279.7 MERGE Statement ........................................................................................................................ 129

    9.7.1.1 Example: MERGE .......................................................................................................... 129

    Lab Week 10 Views ........................................................... ................................................................. ... 13110.1 Objectives ..................................................... ................................................................. .............. 131

    10.1.1 Reference ......................................................... ................................................................. ... 13110.1.2 Database .............................................................................................................................. 131

    10.2 Background of Views .................................................................................................................. 13110.3 Simple View ................................................................................................................................ 132

    10.3.1.1 Example: Simple View ................................................................................... .............. 13210.4 Complex View ............................................................................................................... .............. 133

    10.4.1.1 Example: Complex View .............................................................................................. 13310.5 Dropping a View.......................................................................................................................... 134

    10.5.1.1 Example: Dropping a View .......................................................................................... 134

    Appendix A Sample Database Structures ........................................................ .................................... 135A.1 Sample Databases ........................................................................................................... .............. 135A.2 HR (Human Resources) Database.............................................................................................. ... 135A.3 The HR Entity Relationship Diagram ....................................................... .................................... 136A.4 The Human Resources (HR) Table Descriptions ............................................................ .............. 136A.4.1 countries Table ................................................................. .......................................................... 136A.4.2 departments Table ................................................................................................................ ...... 136A.4.3 employees Table ............................................................................................... ......................... 137A.4.4jobTable ..................................................... ................................................................. .............. 137A.4.5 job_history Table ......................................................................................................... .............. 137A.4.6 locations Table ................................................................. .......................................................... 138

    A.4.7 regions Table ............................................................................................................................. 138A.5 JustLeeBooks Database ....................................................................................... ......................... 138

    Appendix B Instructions to connect to a server database in Oracle SQL Developer ....................... 139

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    7/146

    vii

    UNSW

    SISTM

    LabManual

    Appendix C Instructions to connect to Oracle SQL Developer Data Modeler ................................. 142

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    8/146

    viii

    UNSW

    SISTM

    Lab Manual

    Table of Figures

    Figure I-1 Data Modelling .............................................................................................. 15

    Figure I-2 Example of Tables in Oracle .......................................................................... 16Figure I-3 Example of a Table ........................................................................................ 16Figure I-4 Basic SQL Developer screen layout .............................................................. 19Figure I-5 Menus for Oracle SQL Developer ................................................................. 20Figure I-6 Icons on the SQL Worksheet Menu Bar ........................................................ 21Figure I-7 Connect to HR Database ................................................................................ 22Figure I-8 Drill Down after Connecting to HR Database ............................................... 22Figure I-9 SQL Worksheet and Output ........................................................................... 23Figure I-10 Enter SQL Statements into SQL Worksheet ................................................ 23Figure I-11 Differences Between the Execute Statement and Run Script Output .......... 24Figure I-12 File Saving Icons .......................................................................................... 24

    Figure 2-1 SELECT ALL statement ............................................................................... 25Figure 2-2 Select One Column Only ............................................................................... 26Figure 2-3 Selecting More Than One Column ................................................................ 26Figure 2-4 List the Column Names of employees table .................................................. 27Figure 2-5 Demonstrate Four Common alias Methods ................................................... 29Figure 2-6 Not using Distinct in the SELECT Statement ............................................... 30Figure 2-7 Using DISTINCT in the SELECT Statement................................................ 30Figure 2-8 An Example of Using Concatenation and Literal Strings ............................. 32Figure 2-9 Single Quotation Mark .................................................................................. 33Figure 2-10 Arithmetic Operation ................................................................................... 34

    Figure 3-1 SELECT - Numeric Column ......................................................................... 35Figure 3-2 SELECT - Character Strings ......................................................................... 36Figure 3-3 SELECT - Date Values ................................................................................. 36Figure 3-4 Condition based on Numeric Value .............................................................. 39Figure 3-5 Condition is based on Non-inclusive Values ................................................ 39Figure 3-6 Condition is based on Inclusive Values ........................................................ 40Figure 3-7 Using BETWEEN ... AND ... operator ......................................................... 40Figure 3-8 Selecting based on Character Strings ............................................................ 41Figure 3-9 Compare with Alphanumeric Values ............................................................ 41Figure 3-10 Demonstrate how the Values are selected based on the ASCII Code ......... 42Figure 3-11 Select a range of Character String Values ................................................... 42Figure 3-12 Select a range of Character String Values using BETWEEN ... AND

    ........................................................................................................................... 43Figure 3-13 Using BETWEEN ... AND ... operator But the Lower Limit is not

    First ................................................................................................................... 43Figure 3-14 Demonstrate Case Sensitieve of Value Entered .......................................... 43Figure 3-15 Month Component is not Case Sensitive .................................................... 44Figure 3-16 The use of (Not Equal) Operator........................................................ 44Figure 3-17 The use of NOT Operator......................................................................... 45Figure 3-18 Testing a NULL value ................................................................................. 45Figure 3-19 Using LIKE operator ................................................................................... 46

    Figure 3-20 Using Wildcard Characters in LIKE operator ............................................. 47Figure 3-21 Pattern Matching on Numbers and Date Values ......................................... 47

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    9/146

    ix

    UNSW

    SISTM

    LabManual

    Figure 3-22 Sort by Numeric and Date Values ............................................................... 49Figure 3-23 Sort the Column in Descending Order ........................................................ 50Figure 3-24 NULL Values appear End of the List .......................................................... 50Figure 3-25 Using NULLS FIRST .................................................................................. 50

    Figure 4-1 Examples of using Case Conversion Function .............................................. 52Figure 4-2 An example of using Character Manipulation Functions .............................. 53Figure 4-3 Examples of using ROUND and TRUNC Functions .................................... 54Figure 4-4 Examples of using ABS and POWER Functions .......................................... 54Figure 4-5 Example of using DATE function ................................................................. 55Figure 4-6 Using NVL Function ..................................................................................... 57Figure 4-7 Example of NVL2 Function .......................................................................... 57Figure 4-8 Example of using NULLIF and NULLS FIRST ........................................... 58Figure 4-9 Examples of using TO_CHAR ...................................................................... 58Figure 4-10 Example of using SOUNDEX ..................................................................... 59Figure 4-11 An example of using CASE statement ........................................................ 60

    Figure 5-1 Cartesian Joins ............................................................................................... 65Figure 5-2 Using NATUAL JOIN .................................................................................. 68Figure 5-3 NATURAL JOIN using manager_id ............................................................. 69Figure 5-4 An Example using JOIN ... USING clause ................................................... 70Figure 5-5 JOIN USING clause with alias ................................................................. 71Figure 5-6 JOIN ON Clause ....................................................................................... 71Figure 5-7 Using JOIN ... ON ... for Three tables ........................................................... 72Figure 5-8 Using JOIN ... USING ... for Three tables .................................................... 72Figure 5-9 An Example of Non-equality Join ................................................................. 73Figure 5-10 An Example of self-joins ............................................................................. 74Figure 5-11 Using LEFT OUTER JOINS ....................................................................... 75Figure 5-12 An Example of using RIGHT OUTER JOIN .............................................. 76Figure 5-13 An Example using UNION operator ........................................................... 77Figure 5-14 Using UNION operator with two columns removed................................... 78Figure 5-15 An Example of using INTERSECT Operator ............................................. 79Figure 5-16 Another Example of using INTERSECT Operator ..................................... 79Figure 5-17 An Example using MINUS Operator .......................................................... 80Figure 6-1 An Example of using Group Functions ......................................................... 84Figure 6-2 Find Minimum and Maximum Date Values.................................................. 85Figure 6-3 Count non-NULL values ............................................................................... 85Figure 6-4 Count NULL values ...................................................................................... 86

    Figure 6-5 An Example of Handling NULL values ........................................................ 86

    Figure 6-6 An Example of using GROUP BY ................................................................ 87Figure 6-7 Total of All Records ...................................................................................... 87Figure 6-8 An Example of using GROUP BY and WHERE Clauses ............................ 88Figure 6-9 An Example of using GROUP BY and HAVING Clauses ........................... 88Figure 6-10 An Example of Complex Queries ............................................................... 89Figure 6-11 An Example of Complex Group By ............................................................ 89Figure 6-12 An Example of Complex GROUP BY/HAVING ....................................... 90Figure 7-1 CREATE a new table .................................................................................... 92Figure 7-2 Oracle SQL Developer Layout ...................................................................... 92Figure 7-3 CREATE TABLE AS ......................................................................... 93

    Figure 7-4 ALTER TABLEAdd, Modify and Drop ................................................... 94Figure 7-5 ALTER TABLE SET UNUNSED and DROP........................................ 96

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    10/146

    x

    UNSW

    SISTM

    Lab Manual

    Figure 7-6 Create a New Table with Constraints .......................................................... 100Figure 7-7 Unique Key Violation ................................................................................. 102Figure 7-8 An Example of adding a CHECK Constraint .............................................. 103Figure 7-9 Dropping Constraints .................................................................................. 104

    Figure 8-1 Before Inserting New Records into countries table .................................... 106Figure 8-2 Including and Not including columns in the INSERT statement ................ 106Figure 8-3 Cannot INSERT the Same Record Again ................................................... 107Figure 8-4 COMMIT options ........................................................................................ 107Figure 8-5 Inserting Upper and Lower Text for the Primary Key column ................... 108Figure 8-6 ROLLBACK Options .................................................................................. 108Figure 8-7 Foreign Key Violation ................................................................................. 109Figure 8-8 Assign default or NULL value to a column ................................................ 109Figure 8-9 Insert a new row from an existing table ...................................................... 110Figure 8-10 Update Data ............................................................................................... 111Figure 8-11 Update Without WHERE clause ............................................................... 112

    Figure 8-12 Using Substitution Variables ..................................................................... 113Figure 8-13 Variables Substituted with Entered Values ............................................... 113Figure 8-14 Invalid country id ...................................................................................... 114Figure 8-15 Delete a Record ......................................................................................... 114Figure 8-16 Exit without Updatea Popup Box prompts for Action .......................... 115Figure 9-1 Single-Row Subquery in a WHERE Clause ............................................... 120Figure 9-2 Single-Row Subquery in a HAVING Clause .............................................. 121Figure 9-3 Single-Row Subquery in a SELECT Clause ............................................... 121Figure 9-4 Using the IN Operator ................................................................................. 122Figure 9-5 Using the ALL Operator.............................................................................. 123Figure 9-6 Using the ANY Operator ............................................................................. 124Figure 9-7 Departments Average Salary..................................................................... 125Figure 9-8 Subquery using JOIN in the From clause .................................................... 126Figure 9-9 Subquery in the WHERE clause ................................................................. 126Figure 9-10 Order of Execution in Nested Subqueries ................................................. 127Figure 9-11 Correlated Subqueries ............................................................................... 128Figure 9-12 Correlated Subqueries using EXISTS clause ............................................ 128Figure 9-13 MERGE Statement - Create temporary tables .......................................... 129Figure 9-14 MERGE Statement - List Records in the temporary tables....................... 130Figure 9-15 MERGE Statement - List Changes in temporary tables ............................ 130Figure 10-1 An Example of a Simple View .................................................................. 132

    Figure 10-2 An Example of a Complex View .............................................................. 133

    Figure 10-3 Using WHERE Clause in a VIEW ............................................................ 134Figure 10-4 Dropping a View ....................................................................................... 134

    Figure A-1 ER Diagram for HR Database .................................................................... 136Figure A-2 JustLeeBooks ER Diagram ........................................................................ 138

    Figure B-1 Select Configure File Type Associations ................................................... 139Figure B-2 Server Database Connection Form ............................................................. 139Figure B-3 Database Connection Details ...................................................................... 140Figure B-4 Sample Tables ............................................................................................. 141

    Figure B-5 Set Date Format .......................................................................................... 141

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    11/146

    xi

    UNSW

    SISTM

    LabManual

    Figure C-1 Select Option to import a Data Dictionary ................................................. 142Figure C-2 Connect to an existing database .................................................................. 143Figure C-3 Select a Database ........................................................................................ 143Figure C-4 Select a Schema .......................................................................................... 144

    Figure C-5 Select Six Tables......................................................................................... 144Figure C-6 Summary of Number of Imported Tables ................................................... 145Figure C-7 A Successful Log ........................................................................................ 145Figure C-8 ERD for the Selected Tables....................................................................... 146

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    12/146

    xii

    UNSW

    SISTM

    Lab Manual

    Table of Tables

    Table 2-1 Data Types ...................................................................................................... 28Table 2-2 Arithmetic Operations .................................................................................... 34

    Table 3-1 Logical Operators ........................................................................................... 37Table 3-2 Mathematical Comparison Operators ............................................................. 38Table 3-3 Other Comparison Operators .......................................................................... 38Table 3-4 Evaluation Order ............................................................................................. 48Table 4-1 Type of Function............................................................................................. 51Table 4-2 Case Conversion Functions ............................................................................ 51Table 4-3 Character Manipulation Functions ................................................................. 52Table 4-4 Table of Common Number Functions ............................................................ 53Table 4-5 Table of Common Other Functions ................................................................ 56Table 5-1 Definition of Algebra Operators ..................................................................... 62Table 5-2 Desription of the Set Operators ...................................................................... 77

    Table 6-1 Group 13 and 14 ............................................................................................. 81Table 6-2 Average Mark for all students ........................................................................ 82Table 6-3 Average at Group Level.................................................................................. 82Table 6-4 Finding the average mark with WHERE clause and HAVING clause .......... 83Table 6-5 Using WHERE Clause and HAVING Clause ................................................ 83Table 7-1 Table of Types of Constraint .......................................................................... 99Table 9-1 Five common types of Subquery .................................................................. 120Table 9-2 ALL and ANY Operator Combinations ....................................................... 122Table 10-1 Four Types of Views .................................................................................. 131

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    13/146

    13

    UNSW

    SISTM

    LabManual

    Introduction to Oracle and Relational Database

    History of Oracle

    More than three decades ago, Larry Ellison and co-founders of Oracle Corporation, BobMiner and Ed Oates, committed to building a relational database for business. Now

    more than ever before, Oracle technology can be found in nearly every industry, and in

    the data centres of the Fortune Global 100 companies. Oracle is the first software

    company to develop and deploy 100% internet-enabled enterprise software across its

    entire product line: database, business applications, application development, and

    decision support tools. After the acquisition of Sun, Oracle now also manages the

    download servers for the popular community database MySQL.

    History of SQL

    Dr. E. F. Codd published the paper, A Relational Model of Data for Large Shared Data

    Banks," in June 1970 in the Association of Computer Machinery (ACM) journal,

    Communications of the ACM. Codds model is now accepted as the definitive model for

    relational database management systems (RDBMS). The language, Structured English

    Query Language (SEQUEL) was developed by IBM Corporation, Inc., to use Codds

    model. SEQUEL later became SQL (still pronounced sequel). In 1979, Relational

    Software, Inc. (now Oracle) introduced the first commercially available implementation

    of SQL. Today, SQL is accepted as the standard RDBMS language.

    SQL Standards

    Oracle strives to comply with industry-accepted standards and participates actively in

    SQL standards committees. Industry-accepted committees are the American National

    Standards Institute (ANSI) and the International Organization for Standardization (ISO),

    which is affiliated with the International Electrotechnical Commission (IEC). Both

    ANSI and the ISO/IEC have accepted SQL as the standard language for relational

    databases. When a new SQL standard is simultaneously published by these

    organisations, the names of the standards conform to conventions used by the

    organisation, but the standards are technically identical.The latest SQL standard was adopted in July 2003 and is often called SQL:2003 (revised

    in 2006). Oracle 11g is conformed to the Core SQL:2003 standards (see

    http://docs.oracle.com/cd/B28359_01/server.111/b28286/ap_standard_sql003.htm#i771

    9). The latest standard is SQL:2008.

    http://docs.oracle.com/cd/B28359_01/server.111/b28286/ap_standard_sql003.htm#i7719http://docs.oracle.com/cd/B28359_01/server.111/b28286/ap_standard_sql003.htm#i7719http://docs.oracle.com/cd/B28359_01/server.111/b28286/ap_standard_sql003.htm#i7719http://docs.oracle.com/cd/B28359_01/server.111/b28286/ap_standard_sql003.htm#i7719http://docs.oracle.com/cd/B28359_01/server.111/b28286/ap_standard_sql003.htm#i7719
  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    14/146

    14

    UNSW

    SISTM

    Lab Manual

    Oracle 11g

    Today, organisations need to support multiple terabytes of information for users who

    demand fast and secure access to business applications round the clock. Oracle database

    is widely used in many large corporations in Australia. The database systems must be

    reliable and must be able to recover quickly in the event of any kind of failure.

    Oracle Database 11gis designed along the following feature areas to help organisations

    manage infrastructure grids easily and deliver high-quality service:

    Manageability: By using some of the change assurance, management automation,

    and fault diagnostics features, the database administrators (DBAs) can increase their

    productivity, reduce costs, minimise errors, and maximise quality of service. Some

    of the useful features that promote better management are Database Replay facility,

    the SQL Performance Analyzer, and the Automatic SQL Tuning facility.

    High availability: By using the high availability features, you can reduce the risk ofdown time and data loss. These features improve online operations and enable faster

    database upgrades.

    Performance: By using capabilities such as SecureFiles, compression for online

    transaction processing (OLTP), Real Application Clusters (RAC) optimisations,

    Result Caches, and so on, you can greatly improve the performance of your

    database. Oracle Database 11g enables organisations to manage large, scalable,

    transactional, and data warehousing systems that deliver fast data access using low-

    cost modular storage.

    Security: Oracle Database 11g helps organisations protect their information with

    unique secure configurations, data encryption and masking, and sophisticated

    auditing capabilities. It delivers a secure and scalable platform for reliable and fast

    access to all types of information by using the industry-standard interfaces.

    Information integration: Oracle Database 11ghas many features to better integrate

    data throughout the enterprise. It also supports advanced information life-cycle

    management capabilities. This helps you manage the changing data in your database.

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    15/146

    15

    UNSW

    SISTM

    LabManual

    Information Systems Courses

    Oracle is chosen as the database to be used for all the Information Systems courses.

    Thus, the Oracle skills you developed will not go to waste. In addition, most Relational

    DataBase Management Systems (RDBMSs) follow a similar structure and adhere to the

    same standards. This means that the skills you obtain in this course will also allow you

    to use other RDBMSs.

    Data Modelling

    The following steps are taken to develop from a conceptual model to implementation of

    a database:

    Figure I-1 Data Modelling

    You will use Entity Relationship (ER) modelling technique to model the data based on a

    conceptual model. Tables will be normalised and created in a database using the ER

    diagrams created from the ER modelling.

    Oracle SQL Developer Data Modeler is a data modeling and database design tool, which

    allows you first to create an ER model, and then use this model to create tables in a

    database. One of the premium features of SQL Data Modeler is allowing reverse-

    engineering of an ER model, i.e. an ER model can be built from a list of selected tables.

    This allows a database developer to check the linkages and constraints of tables in anexisting data model.

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    16/146

    16

    UNSW

    SISTM

    Lab Manual

    Relational Database

    Oracle is a relational database as defined by Codd. A relational database uses relations

    or two-dimensional tables to store data as shown in the following diagram:

    Figure I-2 Example of Tables in Oracle

    A Table

    A relational database contains one or many tables. A table is the basic storage structure

    of an RDBMS (Relational Database Management System). A table is made up of rows

    and columns. The below diagram shows the contents of an employee table:

    Figure I-3 Example of a Table

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    17/146

    17

    UNSW

    SISTM

    LabManual

    The numbers in the diagram indicate the following:

    1.

    A single row, record, or tuple representing all the data required to store for anemployee.

    2. A column or attribute containing the employee number. The employee number

    (employee_id) uniquely identifies an employee in the EMPLOYEE table. In thisexample, the employee number column is designated as theprimary key. A primarykey must contain a value and that value must be unique.

    3.

    A column represents one kind of data in a table; in this example, the data is thesalaries of employees.

    4. A columncontaining the department number, which is also aforeign key. A foreignkey is a column that defines how tables relate to each other. A foreign key refers to a

    primary key or a unique key in the same table or in another table. In this example,department_iduniquely identifies a department in the departmentstable.

    5.

    A field or data value can be found at the intersection of a row and a column. Eachindividual field can only have one value.

    6. A field may have no value in it - this is called a nullvalue. In the employees table,only those employees who have the role of sales representative have a value in thecommission_pct (commission) field. The others have a nullvalue.

    Oracle SQL Statements

    The table below shows the data languages and examples of SQL statements for each

    language. In this course, we will cover DML, TCL and DDL but not DCL.

    Description Example of

    SQL

    Statements

    To Be Covered

    in Lab Week

    Data Manipulation Language (DML): SELECTINSERTUPDATEDELETE

    2, 3, 4, 5, 6, 8

    and 9

    Commands that modify data such as retrievingdata from the databases, entering data, changingdata and deleting data.

    Transaction Control Language (TCL):COMMITROLLBACKSAVEPOINT

    8Commands that control transactional processingin a database.

    Data Definition Language (DDL): CREATEALTERDROPRENAME

    7, 9 and 10Commands that define structures in a database,such as create, alter and delete tables.

    Data Control Language (DCL):GRANTREVOKE

    -Commands that control access to rights the dataand tables in a database.

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    18/146

    18

    UNSW

    SISTM

    Lab Manual

    Lab/Tutorial Arrangement

    (1) The tutor will start by demonstrating and discussing the lab materials.

    (2) The SQL script created for the demonstration can be downloaded from

    Blackboard. You are encouraged to run the script yourself to ensure you

    understand the concept. You are also encouraged to experiment and make

    changes to the script yourself - this will help you to understand the SQL

    statements. If you have any questions, you can ask your tutor.

    (3) The lab exercises will help you to develop your SQL knowledge and skills.

    You are not expected to finish all the questions in the lab but you are expected

    to finish the lab exercises as part of your 10-hour workload for the course.

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    19/146

    19

    UNSW

    SISTM

    LabManual

    Introduction to Oracle SQL Developer

    In this course, we will use Oracle SQL Developer as a graphical tool to connect to our

    Oracle database. By default, it uses the Java Database Connectivity (JDBC) thin driver.

    You can also freely download the Oracle SQL Developer application from the Oracle

    website - see:

    http://www.oracle.com/technetwork/developer-tools/sql-developer

    The lab materials were originally written using SQL Developer 2.1.1.64, and version

    3.0.04 was used in the latest revision. It is strongly recommended that you do not install

    either the Alpha, Beta, or Early Adopter version. You can use the latest available version

    of Oracle SQL Developer but the screen shots in this manual might look different from

    your screen, but the fundamental ideas and functionality will be the same.

    The basic Oracle SQL Developer screen layout is shown inFigure I-4.

    Figure I-4 Basic SQL Developer screen layout

    The most important regions of the SQL Developer window are highlighted:

    1. The list of available database connections. Please note 1a. indicates which database

    the SQL commands you have entered will be executed in.

    2.

    The SQL worksheet where SQL commands are entered.

    3. The execute button, which allows you to run the SQL commands you have entered.

    4.

    The results panels which show you the results of your SQL commands in different

    formats.

    http://www.oracle.com/technetwork/developer-tools/sql-developerhttp://www.oracle.com/technetwork/developer-tools/sql-developerhttp://www.oracle.com/technetwork/developer-tools/sql-developer
  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    20/146

    20

    UNSW

    SISTM

    Lab Manual

    SQL commands need to be run within the context of a specific database. The following

    section describes the layout and functionality of the SQL Developer application in more

    detail, the process for connecting to a database and the process for executing SQL

    commands.

    SQL Developer Layout and Functionality

    We will now work through some of the commonly used icons and functions of SQL

    Developer. We will not able to cover all the icons, buttons and function in this course

    but you are encouraged to explore the tools yourself you can get more information

    from Oracle SQL Developer User Guide, which you can download from the link as

    mentioned in the previous section.

    Figure I-5 Menus for Oracle SQL Developer

    Apart from the standard options of File, Edit and Help, the other options on the Menus

    as shown in above are summarised as:

    (a)View: Contains options that affect what is displayed in the Oracle SQL

    Developer interface

    (b)

    Navigate: Contains options for navigating to various panes and for executing

    subprograms

    (c)Run: Contains the Run File and Execution Profile options that are relevant when

    a function or procedure is being executed, debugged or profiled

    (d)

    Versioning: Provides integrated support for the following versioning and source

    control systems such as: Concurrent Versions System (CVS) and Subversion

    (e)Tools: Invokes SQL Developer tools such as SQL*Plus, Preferences, and SQL

    Worksheet

    Some of the common options on the Menu bar can also be executed using short-cut key

    (for example, Ctrl-Cto copy) or by clicking an icon on the menu.

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    21/146

    21

    UNSW

    SISTM

    LabManual

    The icons on the SQL Worksheet menu bar in Figure I-6 are used to execute and

    manipulate the SQL statement(s) that you have entered into the SQL worksheet.

    Figure I-6 Icons on the SQL Worksheet Menu Bar

    Note the number associated with each icon. The functionality of each button, using the

    number as the key, is described:

    1. Execute Statement (Ctrl-Enter): Execute the statement where the cursor islocated in the Enter SQL Statementbox

    2. Run Script (F5): Execute all statements in the Enter SQL Statementbox byusing the Script Runner

    3.

    Autotrace (F6): Generate trace information for the statement4. Execute Explain Plan (F10): Generate the execution plan, which you can seeby clicking the Explain tab.

    5. Commit (F11): Write any changes to the database and ends the transaction6.

    Rollback (F12): Discard any changes to the database, without writing them tothe database, and ends the transaction.

    7.

    Unshared SQL Worksheet8. Change Case: Change word to Uppercase, Lowercase or InitCap9.

    Clear (Ctrl-D): Erase the statement or statements in the Enter SQL Statementbox

    10.SQL History (F8): Display a dialog box with information about SQL

    statements that you have executed

    Connecting to a Database

    There are two sample databases which you will use in the lab:

    (i) Human Resources (HR) database (provided by Oracle) and

    (ii)JustLeeBooks database (provided by Casteel1).

    The lab materials are written based on the HR database, and the lab and homework

    exercises are based on the JustLeeBooks database. You can find the data structures of

    these two databases inAppendix A.

    Instructions to Connect to a Database

    The instructions to connect to a database in Oracle SQL Developer can be found in

    Appendix B.Your password will be given to you.

    1Casteel, Joan, Oracle 11g: SQL, 2010, Cengage Learning.

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    22/146

    22

    UNSW

    SISTM

    Lab Manual

    Reference

    Apart from the instructions given in this manual, you can also find an overview of

    Oracle SQL Developer in Casteel Appendix B, and full users guide in Oracle SQL

    Developer UsersGuide(which you can download from Blackboard or Oracle website).

    Open a Database

    For the purposes of this example we will be connecting to the HR database, but the same

    procedure is used to connect to other databases. Click on HR database icon highlighted

    inFigure I-7 and SQL Developer will try to connect you to the HR database. It will ask

    you for a password, which will be provided to you. The other database you will use for

    the lab exercises is JustLeeBooks database. The tables for JustLeeBooks are also listed

    in HR database and all the tables begin with ZJLB_.

    Figure I-7 Connect to HR Database

    Once you have connected to the database, you can get more details about the database

    by clicking the +button.Figure I-8 shows we have drilled down to the region table.

    Figure I-8 Drill Down after Connecting to HR Database

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    23/146

    23

    UNSW

    SISTM

    LabManual

    Executing SQL Statements in Oracle SQL Developer

    After connecting to the desired database, you can enter SQL statements in the SQL

    Worksheet. Figure I-9 shows the SQL Worksheet in the upper box and the SQL

    statements output in the lower box.

    Figure I-9 SQL Worksheet and Output

    After you have connected to the HR database, for example, you can enter the SQL

    statements in the SQL Worksheet as shown inFigure I-10.

    Figure I-10 Enter SQL Statements into SQL Worksheet

    Once you are satisfied with the SQL statements. In Step 3, you can execute the

    statements by either clicking the Execute Statement icon (or Ctrl-Enter) or Run Script

    icon (or F5). The differences between the two outputs are shown inFigure I-11.On the

    left hand side, clicking Execute Statement icon will generate a Spreadsheet like output

    a query result - whereas on the right hand side, Run Script icon will generate a plain text

    outputa script outputand, moreover, you can save the script output.

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    24/146

    24

    UNSW

    SISTM

    Lab Manual

    Figure I-11 Differences Between the Execute Statement and Run Script Output

    You can save your SQL statements to a new or an existing file by clicking one of thetwo icons on the menu bar as shown inFigure I-12.The file type you select must be.sql.

    Figure I-12 File Saving Icons

    Summary

    In summary, there are four basic steps to run SQL statements in Oracle SQL Developer

    as shown inFigure I-4:

    Step 1: Connect to the desired database, in the diagram the HR database is selected.

    Please note 1a will show the current database you are connected to.

    Step 2: Enter your SQL statement.

    Step 3: Click on the Run Script icon to execute your SQL statement.

    Step 4: The results of your executed SQL statement.

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    25/146

    25

    UNSW

    SISTM

    LabManual

    Lab Week 2Basic SQL SELECT statements

    2.1 Objectives

    For the next few labs, you will learn some of the basic commands of Data Manipulation

    Language (DML) using Oracle database. You will be introduced to Oracle SQL

    Developer as a graphical tool to connect to the Oracle database. At the end of this lab,

    you should know how to retrieve data from a database using Oracle SQL Developer.

    2.1.1Reference

    Casteel Chapter 2

    2.1.2Database

    The database used in this lab is HR database.

    2.2 SELECT Statement

    A SELECT statement is used to retrieve data from the database. It is sometimes also

    called a query because you ask the database a question. In this course, we will cover

    most of the syntaxes in the SELECT statement. You can find the data structure of the

    HR database inAppendix A.

    2.2.1Selecting All Data from a Table

    You can use an asterisk (*) to indicate you want to select all columns from a table:

    SELECT * FROM table_name;

    2.2.1.1 Example:Selecting Al l Data fr om a Table

    You can enter SELECT * FROM employees;in the SQL Worksheet (1) and click on

    the Run Script icon (2) as shown in below figure (Figure 2-1):

    Figure 2-1 SELECT ALL statement

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    26/146

    26

    UNSW

    SISTM

    Lab Manual

    2.3 Selecting a Column or Columns from a Table

    Instead of retrieving all the columns from a table, you may only want to retrieve a few

    by specifying the columns you want separated by commas:

    SELECT column_name, column_name, column_name

    FROM table_name;

    2.3.1.1 Example:Selecting One Column Onl y

    Instead of selecting all columns, you can select, say, one column from the table as

    shown below (Figure 2-2):

    Figure 2-2 Select One Column Only

    2.3.1.2 Example:Selecting More Than One Column

    Instead of selecting just one column, you can select two or more columns by separating

    the columns with comma as shown below (Figure 2-3):

    Figure 2-3 Selecting More Than One Column

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    27/146

    27

    UNSW

    SISTM

    LabManual

    2.3.2Viewing Table Structure

    To list the column names of a table, you can use the command:

    DESC[RIBE] table_name [;]

    2.3.2.1 Example:

    F ind the Column Names of a Table

    For example, you want to find the column names of the employees table (Figure 2-4):

    Figure 2-4 List the Column Names of employees table

    2.3.3Null Values

    Looking at the data structure of employees table as listed above (Figure 2-4), we can see

    there are three columns:

    (a)The Namecolumn contains the column names of the employees table.(b)Nullcolumn indicates whether the column is allowable to have a NULL value.(c)Typedescribes the data type of a column.

    (a) Name

    Column names of a table.

    (b) NULL values

    Null is a special value that is used to represent value unknown or value

    inappropriate. Null is not same as a space () or a zero (0).

    The question is why do we need a NULL value?

    For example, last summer, one student turned up to his examination but did not

    write anything. In this case, the student was awarded a mark of zero (0). On the

    other hand, a student did not turn up to his examination. No mark was awardedfor his examination, i.e. the examination mark column will have a Null value.

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    28/146

    28

    UNSW

    SISTM

    Lab Manual

    Depending on which output option is selected in the Oracle SQL Developer, Null value

    is presented differently. In the Query Output (see diagram below), you will see the literal

    (null) value for employee King. On the other hand, a blank appears when Script

    Output option is selected.

    Using Query Output Option Using Script Output Option

    (c) Data Types

    Every column needs to be defined with a data type. The common data types are listed in

    the following table (Table 2-1):

    Table 2-1 Data Types

    Date Type Description Example

    Number Number without decimal Number (5) = 99999

    Number(n,m) Number with decimal Number(8,2) = 999999.99

    CHAR(n) Fixed length character string of length ncharacters

    Char(2) = AB

    VARCHAR2(n) Variable length character string ofmaximum length of n characters

    VARCHAR(5) = abc

    Date Date Date = 01-JAN-2011

    Difference between CHAR(n) and VARCHAR2(n)

    The difference between CHAR(n) and VARCHAR2(n) is how a character is physicallystored. For CHAR(n), it will allocate n physical storage spaces whereas for

    VARCHAR2(n), the physical space varies depending on the number of characters it

    needs to store. For example, VARCHAR2(5) = abc requires three storage spaces.

    Normally, you use data type CHAR(n) when you have an alpha-numeric field that you

    would like to use as a primary or a foreign key. This is because the extra processing that

    the database needs to do in order to handle a variable-length field can be especially

    detrimental to performance when that field is being used as a primary or foreign key.

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    29/146

    29

    UNSW

    SISTM

    LabManual

    2.4 SELECT Statement

    You can change the display column heading using a column alias. There are three

    common alias methods:

    SELECT column_name_1 AS New_Column_Heading_1,column_name_2 New_Column_Heading_2,

    column_name_3 New Column Heading 3

    column_name_4 AS New Column Heading 4

    FROM employees;

    The first two column alias methods give the columns a new column heading. The use of

    AS keyword is optional. However, you cannot have a space between the words of the

    alias in the first two methods.

    By default, the headings appear in uppercase. If the alias contains a space, a special

    character (e.g. $) or you want the heading appears as upper and lowercase (e.g. First

    Name), then you need to enclose with double quotes ()as shown in the third column

    alias method. The last common alias is using the AS keyword and double quotes.

    2.4.1.1 Example:-- Demonstrate Four Common Al ias Methods

    If you run the following query:

    SELECT employee_id AS Employee,

    employee_id AS "Employee Id",

    last_name Surname,

    first_name "First Name"

    FROM employees;

    The new column headings are displayed inFigure 2-5:

    Figure 2-5 Demonstrate Four Common alias Methods

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    30/146

    30

    UNSW

    SISTM

    Lab Manual

    2.5 SELECT DISTINCT Statement

    By default, the SELECT statement will retrieve all the records. If you only want to find

    unique and eliminate duplicate records, you will have to use DISTINCT in the SELECT

    statement.

    SELECT DISTINCT column_name, column_name

    FROM table_name;

    Note: The keyword UNIQUE is same as DISTINCT will return the same results.

    2.5.1.1 Example:Using Distinct

    Instead of retrieving all 107 rows from employees table for all job ids as shown in

    Figure 2-6 AD_VP and FI_ACCOUNT are examples of repeated job ids. When

    DISTINCT is used in the SELECT statement, only 19 distinct job ids are retrieved as

    shown inFigure 2-7.

    Figure 2-6 Not using Distinct in the SELECT

    Statement

    Figure 2-7 Using DISTINCT in the SELECT

    Statement

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    31/146

    31

    UNSW

    SISTM

    LabManual

    2.5.2Use DISTINCT for Two or More Columns

    When you use DISTINCT for two or more columns, all distinct combination of the

    columns (not just the first column) will be retrieved.

    For example,

    -- (a) Select only the department_id - returns 12 records

    SELECT DISTINCT department_id FROM employees;

    DEPARTMENT_ID

    -------------

    100

    30

    10

    12 rows selected

    -- (b) Select only the manager_idreturns 19 records

    SELECT DISTINCT manager_id FROM employees;

    MANAGER_ID

    ----------

    100

    123

    146

    103

    122

    19 rows selected

    -- (c) Select combination of department_id and manager_idreturns 28 records

    SELECT DISTINCT department_id, manager_id FROM employees;

    DEPARTMENT_ID MANAGER_ID

    ---------------------- ----------------------

    60 103

    80 146

    20 201

    110 101

    28 rows selected

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    32/146

    32

    UNSW

    SISTM

    Lab Manual

    2.6 SELECT and Statement

    A concentration operator, represented by two vertical bars (||), combines the contents of

    two columns together.

    A literal can be a character, a number or a date but it is not a column name or a column

    alias. The literal is treated like a column, and it will appear for every row that is

    retrieved. The date and character literals mustbe enclosed between single quotation

    marks () but not for numeric literals.

    SELECT column_name ||Literal Strings|| column_nameFROM table_name;

    2.6.1.1 Example:Using Concatenation and L iteral Stri ngs

    Figure 2-8 An Example of Using Concatenation and Literal Strings

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    33/146

    33

    UNSW

    SISTM

    LabManual

    2.6.1.2 Example:Single Quotation Mark

    If you want to include a single quotation mark as part of the literal, you must use the

    quote (q) operator and select your own quotation mark delimiter such as [ ], { }, ( ), or .

    For example, qis for s job id is as shown below (Figure 2-9):

    Figure 2-9 Single Quotation Mark

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    34/146

    34

    UNSW

    SISTM

    Lab Manual

    2.7 Arithmetic Operations

    You can perform calculations using four basic arithmetic operators, which are shown in

    Table 2-2.These arithmetic expressions can be used to modify the value of fields used

    in or returned by your select statements. Arithmetic operations are executed using

    normal operator precedence, i.e. according to their order of execution priority (listed in

    the table below) moving from left to right in the equation. Parentheses ( ) can be

    used to change the order of execution. You are encouraged to use parentheses to make

    the equation more readable and avoid confusion when two or more operators are used.

    For instance, if you have an equation salary + 12 * 100: do you mean (salary + 12) * 100

    or salary + (12 * 100)? You will find using parentheses help to resolve any ambiguity

    that might arise.

    Table 2-2 Arithmetic Operations

    Operator Order ofExecution

    Multiplication * 1

    Division / 2

    Addition + 3

    Subtraction - 4

    SELECT column_name FROM table_name;

    2.7.1.1 Example:

    Ar ithmetic OperationFigure 2-10 shows all employees are given 10% pay rise and an extra $100 per month:

    Figure 2-10 Arithmetic Operation

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    35/146

    35

    UNSW

    SISTM

    LabManual

    Lab Week 3Restricting Rows and Sorting Data

    3.1 Objectives

    Today, we continue to look at the SELECT statement:

    To limit the rows retrieved by a query -

    o using the WHERE clause,

    o using comparison and

    o Logical operators.

    To sort the rows retrieved by a query

    3.1.1Reference

    Casteel Chapter 8

    3.1.2DatabaseThe database used in this lab is HR database.

    3.2 SELECT Statement

    In the WHERE clause, you can define a condition to retrieve rows from a table.

    SELECT column_name, column_name

    FROM table_name

    WHERE (condition);

    3.2.1Numeric, Character Strings and Dates

    The most common types of column are numeric, character strings and dates. There are

    other, less commonly used types, for storing other types of data which we do not cover

    in this course. For instance, the blobtype can be used to store pictures.

    3.2.1.1 Example:Numeri c Values

    You can retrieve rows by specifying a specific numeric value:

    Figure 3-1 SELECT - Numeric Column

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    36/146

    36

    UNSW

    SISTM

    Lab Manual

    3.2.1.2 Example:Character Stri ngs

    When using character strings in the WHERE clause, you have to enclose the string with

    single quotation marks () and it is case sensitive.

    Figure 3-2 SELECT - Character Strings

    3.2.1.3 Example:

    Date Values

    The date values in the WHERE clause are enclosed with single quotation marks ( ),

    format-sensitive and the default date display format is DD-MON-RR (e.g. 16-JAN-11).

    Figure 3-3 SELECT - Date Values

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    37/146

    37

    UNSW

    SISTM

    LabManual

    3.3 Logical Operators

    The three logical operators used to test in the condition are (examples based on Table

    3-1):

    ANDboth conditions must be true

    o

    If A=B is true AND C=D is true, then the conditionis true.

    ORat least one condition must be true

    o Either A=B is true OR C=D is true, then the conditionis true.

    NOTreverses of the initial result

    o If A=B is true, then NOT(A=B) becomes false

    Table 3-1 Logical Operators

    Operators Result

    A=B C=D

    TRUE TRUE TRUE

    TRUE FALSE FALSE

    FALSE TRUE FALSE

    FALSE FALSE FALSE

    TRUE TRUE TRUE

    TRUE FALSE TRUE

    FALSE TRUE TRUE

    FALSE FALSE FALSE

    Operator Condition Result

    A=B

    TRUE FALSE

    FALSE TRUENOT

    Condition

    AND

    OR

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    38/146

    38

    UNSW

    SISTM

    Lab Manual

    3.4 Comparison Operators

    Comparison operators are used in the condition to compare columns, values and/or

    expressions. The two tables (Table 3-2 and Table 3-3)show the operators that can be

    used for comparisons:

    Table 3-2 Mathematical Comparison Operators

    Table 3-3 Other Comparison Operators

    Now, we demonstrate examples using some of the operators inTable 3-1,Table 3-2 and

    Table 3-3.

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    39/146

    39

    UNSW

    SISTM

    LabManual

    3.4.1.1 Example:Condition based on Numer ic Value

    A simple example of selecting numeric value (Figure 3-4):

    Figure 3-4 Condition based on Numeric Value

    When to use the operator greater than(>) or greater than or equal to(>=) depends onhow you want to evaluate the values.Figure 3-5 andFigure 3-6 show different values

    are retrieved based on different operators. 10,000 and 11,000 were retrieved in Figure

    3-6but not inFigure 3-5.Alternatively, you can use BETWEEN ... AND ... operator.

    Values that are specified using the BETWEEN ... AND ... operator are considered as

    inclusivethus, the results inFigure 3-6 andFigure 3-7 should be same.

    Figure 3-5 Condition is based on Non-inclusive Values

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    40/146

    40

    UNSW

    SISTM

    Lab Manual

    Figure 3-6 Condition is based on Inclusive Values

    Figure 3-7 Using BETWEEN ... AND ... operator

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    41/146

    41

    UNSW

    SISTM

    LabManual

    3.4.1.2 Example:Condition based on Character Str ings

    Figure 3-8 Selecting based on Character Strings

    Figure 3-9 Compare with Alphanumeric Values

  • 8/12/2019 INFS1603 Lab Manual (v1.11)

    42/146

    42

    UNSW

    SISTM

    Lab Manual

    When comparison is done between two values, the values are compared using ASCII

    codes (see http://www.asciitable.com). ASCII stands for American Standard Code for

    Information Interchange. ASCII code represents a number which the computer or

    software could translate.

    In Figure 3-10, postal_