INFS1603 Lab Manual (v1.11)

August 22, 2017 | Author: Danilo Scodellaro | Category: Sql, Oracle Database, Data Management, Databases, Data Model
Share Embed Donate


Short Description

Oracle SQL...

Description

Australian School of Business School of Information Systems, Technology and Management

ORACLE LAB MANUAL

UNSW SISTM Lab Manual

Document Update: Author Vincent Pang Vincent Pang

Date Feb, 2011 Dec, 2011

SQL Developer Version 2.1.1.64 3.0.04

Version v1.00 v1.11

References: The following referencing materials were used to create this Oracle Lab Manual: (1) (2) (3) (4) (5) (6)

Casteel, Joan, Oracle 11g: SQL, 2010, Cengage Learning Oracle Database: SQL Fundamentals I, Oracle Education Oracle Database: SQL Fundamentals II, Oracle Education Oracle SQL Developer 2.1 User’s Guide, Oracle Http://www.oracle.com 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.

ii

UNSW SISTM Lab Manual

Table of Contents Table of Contents ...................................................................................................................................... iii Table of Figures ....................................................................................................................................... viii Table of Tables ......................................................................................................................................... xii Introduction to Oracle and Relational Database ................................................................................... 13 History of Oracle ................................................................................................................................... 13 History of SQL ...................................................................................................................................... 13 SQL Standards ....................................................................................................................................... 13 Oracle 11g ............................................................................................................................................. 14 Information Systems Courses ................................................................................................................ 15 Data Modelling ...................................................................................................................................... 15 Relational Database ............................................................................................................................... 16 A Table .................................................................................................................................................. 16 Oracle SQL Statements.......................................................................................................................... 17 Lab/Tutorial Arrangement ..................................................................................................................... 18 Introduction to Oracle SQL Developer .................................................................................................. 19 SQL Developer Layout and Functionality ............................................................................................. 20 Connecting to a Database ...................................................................................................................... 21 Instructions to Connect to a Database ............................................................................................... 21 Reference .......................................................................................................................................... 22 Open a Database ............................................................................................................................... 22 Executing SQL Statements in Oracle SQL Developer .......................................................................... 23 Summary................................................................................................................................................ 24 Lab Week 2 Basic SQL SELECT statements ....................................................................................... 25 2.1 Objectives ........................................................................................................................................ 25 2.1.1 Reference ................................................................................................................................. 25 2.1.2 Database .................................................................................................................................. 25 2.2 SELECT Statement .......................................................................................................................... 25 2.2.1 Selecting All Data from a Table .............................................................................................. 25 2.2.1.1 Example: Selecting All Data from a Table ....................................................................... 25 2.3 Selecting a Column or Columns from a Table ................................................................................. 26 2.3.1.1 Example: Selecting One Column Only ............................................................................. 26 2.3.1.2 Example: Selecting More Than One Column ................................................................... 26 2.3.2 Viewing Table Structure .......................................................................................................... 27 2.3.2.1 Example: Find the Column Names of a Table .................................................................. 27 2.3.3 Null Values .............................................................................................................................. 27 Difference between CHAR(n) and VARCHAR2(n) ........................................................................... 28 2.4 SELECT Statement .............................................................................................. 29 2.4.1.1 Example: -- Demonstrate Four Common Alias Methods.................................................. 29 2.5 SELECT DISTINCT Statement....................................................................................................... 30 2.5.1.1 Example: Using Distinct ................................................................................................... 30 2.5.2 Use DISTINCT for Two or More Columns ............................................................................. 31 2.6 SELECT and Statement .......................................................... 32 2.6.1.1 Example: Using Concatenation and Literal Strings .......................................................... 32 2.6.1.2 Example: Single Quotation Mark ..................................................................................... 33 2.7 Arithmetic Operations ..................................................................................................................... 34 2.7.1.1 Example: Arithmetic Operation ........................................................................................ 34 Lab Week 3 Restricting Rows and Sorting Data .................................................................................. 35 3.1 Objectives ........................................................................................................................................ 35 3.1.1 Reference ................................................................................................................................. 35 3.1.2 Database .................................................................................................................................. 35 3.2 SELECT Statement ........................................................................................... 35 3.2.1 Numeric, Character Strings and Dates ..................................................................................... 35 3.2.1.1 Example: Numeric Values ................................................................................................ 35 3.2.1.2 Example: Character Strings .............................................................................................. 36 3.2.1.3 Example: Date Values ...................................................................................................... 36 3.3 Logical Operators ............................................................................................................................ 37

iii

UNSW SISTM Lab Manual

3.4 Comparison Operators ..................................................................................................................... 38 3.4.1.1 Example: Condition based on Numeric Value .................................................................. 39 3.4.1.2 Example: Condition based on Character Strings .............................................................. 41 3.4.1.3 Example: Condition based on a Date Values .................................................................... 44 3.4.1.4 Example: The use of Not Equal or NOT Operator ........................................................... 44 3.4.1.5 Example: The use of LIKE Operator ................................................................................ 46 3.4.2 Rules of Precedence ................................................................................................................. 48 3.5 SELECT Statement ..................................................................................... 48 3.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 ......................................................................................... 51 4.1 Objectives ........................................................................................................................................ 51 4.1.1 Reference ................................................................................................................................. 51 4.1.2 Database .................................................................................................................................. 51 4.2 Overview of Functions .................................................................................................................... 51 4.2.1 Case Conversion Functions ..................................................................................................... 51 4.2.1.1 Example: Case Conversion Function ................................................................................ 52 4.3 Character Manipulation Functions ................................................................................................... 52 4.3.1.1 Example: Character Manipulation Functions ................................................................... 53 4.4 Number Functions ........................................................................................................................... 53 4.4.1.1 Example: Examples of using Number Functions .............................................................. 54 4.4.2 The Dual Table ........................................................................................................................ 54 4.5 Date Functions ................................................................................................................................. 55 4.5.1.1 Example: Date Function ................................................................................................... 55 4.6 Regular Expressions ........................................................................................................................ 55 4.7 Other Functions ............................................................................................................................... 56 4.7.1.1 Example: Using NVL Functions ....................................................................................... 57 4.8 CASE Expression ............................................................................................................................ 59 Lab Week 5 Joining Data from Multiple Tables .................................................................................. 61 5.1 Objectives ........................................................................................................................................ 61 5.1.1 Reference ................................................................................................................................. 61 5.1.2 Database .................................................................................................................................. 61 5.2 Relational Algebra ........................................................................................................................... 61 5.3 Purpose of Joins ............................................................................................................................... 65 5.3.1 Cartesian Joins ......................................................................................................................... 65 5.4 Using Alias for Tables ..................................................................................................................... 66 5.5 Traditional Join Method versus ANSI JOIN Method ...................................................................... 67 5.6 Equality Joins .................................................................................................................................. 68 5.6.1 NATURAL JOIN Clause ......................................................................................................... 68 5.6.1.1 Example: Using NATURAL JOIN ................................................................................... 68 5.6.2 JOIN … USING Clause ........................................................................................................... 70 5.6.2.1 Example: JOIN … USING Clause with Alias .................................................................. 71 5.6.3 JOIN … ON Clause ................................................................................................................. 71 5.6.3.1 Example: JOIN … ON Clause .......................................................................................... 71 5.7 Non-equality Joins ........................................................................................................................... 73 5.8 Self-Joins ......................................................................................................................................... 74 5.8.1.1 Example: Self-Joins .......................................................................................................... 74 5.8.2 INNER JOINS ......................................................................................................................... 74 5.9 OUTER JOINS ................................................................................................................................ 74 5.9.1 Difference between INNER and OUTER Joins ....................................................................... 74 5.9.2 LEFT OUTER JOIN ................................................................................................................ 75 5.9.2.1 Example: Using LEFT OUTER JOINS ............................................................................ 75 5.9.3 RIGHT OUTER JOIN ............................................................................................................. 76 5.9.3.1 Example: RIGHT OUTER JOIN ...................................................................................... 76 5.9.4 FULL JOIN.............................................................................................................................. 76 5.10 SET OPERATORS ........................................................................................................................ 77 5.10.1 UNION .................................................................................................................................. 77 5.10.1.1 Example: UNION ........................................................................................................... 77 5.10.2 UNION ALL.......................................................................................................................... 78 iv

UNSW SISTM Lab Manual

5.10.3 INTERSECT .......................................................................................................................... 78 5.10.4 MINUS .................................................................................................................................. 80 Lab Week 6 Group Functions ................................................................................................................ 81 6.1 Objectives ........................................................................................................................................ 81 6.1.1 Reference ................................................................................................................................. 81 6.1.2 Database .................................................................................................................................. 81 6.2 Understand Grouping ....................................................................................................................... 81 6.3 SELECT Statement .................................................................................................... 84 6.3.1 Group Functions ...................................................................................................................... 84 6.3.1.1 Example: Group Functions ............................................................................................... 84 6.3.2 Other Data Types ..................................................................................................................... 85 6.3.2.1 Example: Date Values ...................................................................................................... 85 6.3.3 COUNT ................................................................................................................................... 85 6.3.3.1 Example: Using COUNT .................................................................................................. 85 6.3.3.2 Example: Handling NULL Values .................................................................................... 86 6.3.4 Grouping Data ......................................................................................................................... 87 6.3.4.1 Example: GROUP BY ...................................................................................................... 87 6.3.4.2 Example: GROUP BY, ORDER BY, WHERE and HAVING ......................................... 88 6.3.4.3 Example: Complex Queries .............................................................................................. 89 Lab Week 7 Table Creation, Constraints and Management ............................................................... 91 7.1 Objectives ........................................................................................................................................ 91 7.1.1 Reference ................................................................................................................................. 91 7.2 CREATE TABLE Statement ........................................................................................................... 91 7.2.1.1 Example: CREATE a TABLE ......................................................................................... 92 7.2.2 User Tables .............................................................................................................................. 93 7.3 CREATE TABLE … AS … Statement ........................................................................................... 93 7.3.1.1 Example: CREATE TABLE … AS … ............................................................................. 93 7.4 Modifying An Existing Table .......................................................................................................... 94 7.4.1.1 Example: ALTER TABLE – Add, Modify and Drop ....................................................... 94 7.5 ALTER TABLE…SET UNUSED (and DROP) Statement ............................................................. 95 7.5.1.1 Example: ALTER TABLE … SET UNUNSED and DROP ............................................ 96 7.6 Renaming a Table ............................................................................................................................ 96 7.7 Truncating a Table ........................................................................................................................... 97 7.8 Deleting a Table............................................................................................................................... 97 7.9 Constraints ....................................................................................................................................... 98 7.9.1 Create Constraints .................................................................................................................... 99 7.9.2 Create a Table with Constraints ............................................................................................. 100 7.9.2.1 Example: Primary and Foreign Keys in the Statement ................................................... 100 7.9.3 Composite Primary Key ........................................................................................................ 101 7.9.4 Using the UNIQUE Constraint .............................................................................................. 101 7.9.4.1 Example: Unique Key Violation ..................................................................................... 102 7.10 Using the NOT NULL Constraint ............................................................................................... 102 7.11 CHECK Constraint ...................................................................................................................... 103 7.12 Drop Constraints .......................................................................................................................... 103 7.12.1.1 Example: Dropping a Primary Key and Constraints ..................................................... 104 7.13 Enable and Disable Constraints ................................................................................................... 104 Lab Week 8 Data Manipulation Language (DML) and Transaction Control ................................. 105 8.1 Objectives ...................................................................................................................................... 105 8.1.1 Reference ............................................................................................................................... 105 8.1.2 Database ................................................................................................................................ 105 8.2 Data Manipulation Language (DML) Commands ......................................................................... 105 8.2.1 INSERT Command ................................................................................................................ 105 8.2.1.1 Example: Insert a New Row ........................................................................................... 106 8.2.1.2 Example: Primary Key Constraint Violation .................................................................. 107 8.2.1.3 Example: Foreign Key Constraint Violation .................................................................. 109 8.2.1.4 Example: Initialised with Default Values ....................................................................... 109 8.2.2 INSERTING Data from an Existing Table ............................................................................ 110 8.2.2.1 Example: Inserting Data from an Existing Table ............................................................ 110 8.2.3 UPDATE Command .............................................................................................................. 111

v

UNSW SISTM Lab Manual

8.2.4 Substitution Variables ............................................................................................................ 112 8.2.4.1 Example: Using Substitution Variables .......................................................................... 112 8.2.5 DELETE Command............................................................................................................... 114 8.3 Transaction Control Commands .................................................................................................... 115 8.3.1 COMMIT Command ............................................................................................................. 115 8.3.2 ROLLBACK Command ........................................................................................................ 115 8.4 SAVEPOINT and ROLLBACK TO Commands........................................................................... 115 8.4.1.1 Example: Savepoint and Rollback .................................................................................. 116 8.5 Next Sequence Number ................................................................................................................. 117 8.6 Table Locks ................................................................................................................................... 118 8.6.1 LOCK TABLE Command Shared Lock ................................................................................ 118 8.6.2 LOCK TABLE Command Exclusive Lock ........................................................................... 118 8.7 SELECT…FOR UPDATE Command ........................................................................................... 118 Lab Week 9 Subqueries and Merge Statements ................................................................................. 119 9.1 Objectives ...................................................................................................................................... 119 9.1.1 Reference ............................................................................................................................... 119 9.1.2 Database ................................................................................................................................ 119 9.2 Subqueries and Their Uses ............................................................................................................ 119 9.2.1 Single-Row Subquery ............................................................................................................ 120 9.2.1.1 Example: Single-Row Subquery in a WHERE Clause ................................................... 120 9.2.1.2 Example: Single-Row Subquery in a HAVING Clause.................................................. 121 9.2.1.3 Example: Single-Row Subquery in a SELECT Clause ................................................... 121 9.3 Multiple-Row Subqueries .............................................................................................................. 122 9.3.1.1 Example: Using the IN Operator .................................................................................... 122 9.3.1.2 Example: Using the ALL Operator ................................................................................. 123 9.3.1.3 Example: Using the ANY Operator ................................................................................ 124 9.4 Multiple-Column Subqueries ......................................................................................................... 125 9.4.1 Multiple-Column Subquery in a FROM clause ..................................................................... 125 9.4.2 Multiple-Column Subquery in a WHERE clause .................................................................. 126 9.5 Nested Subqueries ......................................................................................................................... 127 9.6 Correlated Subqueries .................................................................................................................... 127 9.6.1.1 Example: Correlated Subqueries ..................................................................................... 127 9.7 MERGE Statement ........................................................................................................................ 129 9.7.1.1 Example: MERGE .......................................................................................................... 129 Lab Week 10 Views ............................................................................................................................... 131 10.1 Objectives .................................................................................................................................... 131 10.1.1 Reference ............................................................................................................................. 131 10.1.2 Database .............................................................................................................................. 131 10.2 Background of Views .................................................................................................................. 131 10.3 Simple View ................................................................................................................................ 132 10.3.1.1 Example: Simple View ................................................................................................. 132 10.4 Complex View ............................................................................................................................. 133 10.4.1.1 Example: Complex View .............................................................................................. 133 10.5 Dropping a View.......................................................................................................................... 134 10.5.1.1 Example: Dropping a View .......................................................................................... 134 Appendix A Sample Database Structures ............................................................................................ 135 A.1 Sample Databases ......................................................................................................................... 135 A.2 HR (Human Resources) Database................................................................................................. 135 A.3 The HR Entity Relationship Diagram ........................................................................................... 136 A.4 The Human Resources (HR) Table Descriptions .......................................................................... 136 A.4.1 countries Table........................................................................................................................... 136 A.4.2 departments Table ...................................................................................................................... 136 A.4.3 employees Table ........................................................................................................................ 137 A.4.4 job Table .................................................................................................................................... 137 A.4.5 job_history Table ....................................................................................................................... 137 A.4.6 locations Table ........................................................................................................................... 138 A.4.7 regions Table ............................................................................................................................. 138 A.5 JustLeeBooks Database ................................................................................................................ 138 Appendix B Instructions to connect to a server database in Oracle SQL Developer ....................... 139 vi

UNSW SISTM Lab Manual

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

vii

UNSW SISTM Lab Manual

Table of Figures Figure I-1 Data Modelling .............................................................................................. 15 Figure I-2 Example of Tables in Oracle .......................................................................... 16 Figure I-3 Example of a Table ........................................................................................ 16 Figure I-4 Basic SQL Developer screen layout .............................................................. 19 Figure I-5 Menus for Oracle SQL Developer ................................................................. 20 Figure I-6 Icons on the SQL Worksheet Menu Bar ........................................................ 21 Figure I-7 Connect to HR Database ................................................................................ 22 Figure I-8 Drill Down after Connecting to HR Database ............................................... 22 Figure I-9 SQL Worksheet and Output ........................................................................... 23 Figure I-10 Enter SQL Statements into SQL Worksheet ................................................ 23 Figure I-11 Differences Between the Execute Statement and Run Script Output .......... 24 Figure I-12 File Saving Icons .......................................................................................... 24 Figure 2-1 SELECT ALL statement ............................................................................... 25 Figure 2-2 Select One Column Only............................................................................... 26 Figure 2-3 Selecting More Than One Column ................................................................ 26 Figure 2-4 List the Column Names of employees table .................................................. 27 Figure 2-5 Demonstrate Four Common alias Methods ................................................... 29 Figure 2-6 Not using Distinct in the SELECT Statement ............................................... 30 Figure 2-7 Using DISTINCT in the SELECT Statement................................................ 30 Figure 2-8 An Example of Using Concatenation and Literal Strings ............................. 32 Figure 2-9 Single Quotation Mark .................................................................................. 33 Figure 2-10 Arithmetic Operation ................................................................................... 34 Figure 3-1 SELECT - Numeric Column ......................................................................... 35 Figure 3-2 SELECT - Character Strings ......................................................................... 36 Figure 3-3 SELECT - Date Values ................................................................................. 36 Figure 3-4 Condition based on Numeric Value .............................................................. 39 Figure 3-5 Condition is based on Non-inclusive Values ................................................ 39 Figure 3-6 Condition is based on Inclusive Values ........................................................ 40 Figure 3-7 Using BETWEEN ... AND ... operator ......................................................... 40 Figure 3-8 Selecting based on Character Strings ............................................................ 41 Figure 3-9 Compare with Alphanumeric Values ............................................................ 41 Figure 3-10 Demonstrate how the Values are selected based on the ASCII Code ......... 42 Figure 3-11 Select a range of Character String Values ................................................... 42 Figure 3-12 Select a range of Character String Values using BETWEEN ... AND ........................................................................................................................... 43 Figure 3-13 Using BETWEEN ... AND ... operator But the Lower Limit is not First ................................................................................................................... 43 Figure 3-14 Demonstrate Case Sensitieve of Value Entered .......................................... 43 Figure 3-15 Month Component is not Case Sensitive .................................................... 44 Figure 3-16 The use of ‘’ (Not Equal) Operator ........................................................ 44 Figure 3-17 The use of ‘NOT’ Operator ......................................................................... 45 Figure 3-18 Testing a NULL value ................................................................................. 45 Figure 3-19 Using LIKE operator ................................................................................... 46 Figure 3-20 Using Wildcard Characters in LIKE operator ............................................. 47 Figure 3-21 Pattern Matching on Numbers and Date Values ......................................... 47 viii

UNSW SISTM Lab Manual

Figure 3-22 Sort by Numeric and Date Values ............................................................... 49 Figure 3-23 Sort the Column in Descending Order ........................................................ 50 Figure 3-24 NULL Values appear End of the List .......................................................... 50 Figure 3-25 Using NULLS FIRST .................................................................................. 50 Figure 4-1 Examples of using Case Conversion Function .............................................. 52 Figure 4-2 An example of using Character Manipulation Functions .............................. 53 Figure 4-3 Examples of using ROUND and TRUNC Functions .................................... 54 Figure 4-4 Examples of using ABS and POWER Functions .......................................... 54 Figure 4-5 Example of using DATE function ................................................................. 55 Figure 4-6 Using NVL Function ..................................................................................... 57 Figure 4-7 Example of NVL2 Function .......................................................................... 57 Figure 4-8 Example of using NULLIF and NULLS FIRST ........................................... 58 Figure 4-9 Examples of using TO_CHAR ...................................................................... 58 Figure 4-10 Example of using SOUNDEX ..................................................................... 59 Figure 4-11 An example of using CASE statement ........................................................ 60 Figure 5-1 Cartesian Joins............................................................................................... 65 Figure 5-2 Using NATUAL JOIN .................................................................................. 68 Figure 5-3 NATURAL JOIN using manager_id ............................................................. 69 Figure 5-4 An Example using JOIN ... USING clause ................................................... 70 Figure 5-5 JOIN … USING clause with alias ................................................................. 71 Figure 5-6 JOIN … ON Clause....................................................................................... 71 Figure 5-7 Using JOIN ... ON ... for Three tables ........................................................... 72 Figure 5-8 Using JOIN ... USING ... for Three tables .................................................... 72 Figure 5-9 An Example of Non-equality Join ................................................................. 73 Figure 5-10 An Example of self-joins ............................................................................. 74 Figure 5-11 Using LEFT OUTER JOINS ....................................................................... 75 Figure 5-12 An Example of using RIGHT OUTER JOIN .............................................. 76 Figure 5-13 An Example using UNION operator ........................................................... 77 Figure 5-14 Using UNION operator with two columns removed................................... 78 Figure 5-15 An Example of using INTERSECT Operator ............................................. 79 Figure 5-16 Another Example of using INTERSECT Operator ..................................... 79 Figure 5-17 An Example using MINUS Operator .......................................................... 80 Figure 6-1 An Example of using Group Functions ......................................................... 84 Figure 6-2 Find Minimum and Maximum Date Values.................................................. 85 Figure 6-3 Count non-NULL values ............................................................................... 85 Figure 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 ................................................................ 87 Figure 6-7 Total of All Records ...................................................................................... 87 Figure 6-8 An Example of using GROUP BY and WHERE Clauses ............................ 88 Figure 6-9 An Example of using GROUP BY and HAVING Clauses ........................... 88 Figure 6-10 An Example of Complex Queries ............................................................... 89 Figure 6-11 An Example of Complex Group By ............................................................ 89 Figure 6-12 An Example of Complex GROUP BY/HAVING ....................................... 90 Figure 7-1 CREATE a new table .................................................................................... 92 Figure 7-2 Oracle SQL Developer Layout ...................................................................... 92 Figure 7-3 CREATE TABLE … AS … ......................................................................... 93 Figure 7-4 ALTER TABLE – Add, Modify and Drop ................................................... 94 Figure 7-5 ALTER TABLE … SET UNUNSED and DROP ........................................ 96

ix

UNSW SISTM Lab Manual

Figure 7-6 Create a New Table with Constraints .......................................................... 100 Figure 7-7 Unique Key Violation ................................................................................. 102 Figure 7-8 An Example of adding a CHECK Constraint .............................................. 103 Figure 7-9 Dropping Constraints .................................................................................. 104 Figure 8-1 Before Inserting New Records into countries table .................................... 106 Figure 8-2 Including and Not including columns in the INSERT statement ................ 106 Figure 8-3 Cannot INSERT the Same Record Again ................................................... 107 Figure 8-4 COMMIT options ........................................................................................ 107 Figure 8-5 Inserting Upper and Lower Text for the Primary Key column ................... 108 Figure 8-6 ROLLBACK Options .................................................................................. 108 Figure 8-7 Foreign Key Violation ................................................................................. 109 Figure 8-8 Assign default or NULL value to a column ................................................ 109 Figure 8-9 Insert a new row from an existing table ...................................................... 110 Figure 8-10 Update Data ............................................................................................... 111 Figure 8-11 Update Without WHERE clause ............................................................... 112 Figure 8-12 Using Substitution Variables ..................................................................... 113 Figure 8-13 Variables Substituted with Entered Values ............................................... 113 Figure 8-14 Invalid country id ...................................................................................... 114 Figure 8-15 Delete a Record ......................................................................................... 114 Figure 8-16 Exit without Update – a Popup Box prompts for Action .......................... 115 Figure 9-1 Single-Row Subquery in a WHERE Clause ............................................... 120 Figure 9-2 Single-Row Subquery in a HAVING Clause .............................................. 121 Figure 9-3 Single-Row Subquery in a SELECT Clause ............................................... 121 Figure 9-4 Using the IN Operator ................................................................................. 122 Figure 9-5 Using the ALL Operator.............................................................................. 123 Figure 9-6 Using the ANY Operator ............................................................................. 124 Figure 9-7 Department’s Average Salary ..................................................................... 125 Figure 9-8 Subquery using JOIN in the From clause .................................................... 126 Figure 9-9 Subquery in the WHERE clause ................................................................. 126 Figure 9-10 Order of Execution in Nested Subqueries ................................................. 127 Figure 9-11 Correlated Subqueries ............................................................................... 128 Figure 9-12 Correlated Subqueries using EXISTS clause ............................................ 128 Figure 9-13 MERGE Statement - Create temporary tables .......................................... 129 Figure 9-14 MERGE Statement - List Records in the temporary tables....................... 130 Figure 9-15 MERGE Statement - List Changes in temporary tables ............................ 130 Figure 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 ............................................................ 134 Figure 10-4 Dropping a View ....................................................................................... 134 Figure A-1 ER Diagram for HR Database .................................................................... 136 Figure A-2 JustLeeBooks ER Diagram ........................................................................ 138 Figure B-1 Select Configure File Type Associations ................................................... 139 Figure B-2 Server Database Connection Form ............................................................. 139 Figure B-3 Database Connection Details ...................................................................... 140 Figure B-4 Sample Tables............................................................................................. 141 Figure B-5 Set Date Format .......................................................................................... 141

x

UNSW SISTM Lab Manual

Figure C-1 Select Option to import a Data Dictionary ................................................. 142 Figure C-2 Connect to an existing database .................................................................. 143 Figure C-3 Select a Database ........................................................................................ 143 Figure C-4 Select a Schema .......................................................................................... 144 Figure C-5 Select Six Tables......................................................................................... 144 Figure C-6 Summary of Number of Imported Tables ................................................... 145 Figure C-7 A Successful Log ........................................................................................ 145 Figure C-8 ERD for the Selected Tables....................................................................... 146

xi

UNSW SISTM Lab Manual

Table of Tables Table 2-1 Data Types ...................................................................................................... 28 Table 2-2 Arithmetic Operations .................................................................................... 34 Table 3-1 Logical Operators ........................................................................................... 37 Table 3-2 Mathematical Comparison Operators ............................................................. 38 Table 3-3 Other Comparison Operators .......................................................................... 38 Table 3-4 Evaluation Order ............................................................................................. 48 Table 4-1 Type of Function............................................................................................. 51 Table 4-2 Case Conversion Functions ............................................................................ 51 Table 4-3 Character Manipulation Functions ................................................................. 52 Table 4-4 Table of Common Number Functions ............................................................ 53 Table 4-5 Table of Common Other Functions ................................................................ 56 Table 5-1 Definition of Algebra Operators ..................................................................... 62 Table 5-2 Desription of the Set Operators ...................................................................... 77 Table 6-1 Group 13 and 14 ............................................................................................. 81 Table 6-2 Average Mark for all students ........................................................................ 82 Table 6-3 Average at Group Level.................................................................................. 82 Table 6-4 Finding the average mark with WHERE clause and HAVING clause .......... 83 Table 6-5 Using WHERE Clause and HAVING Clause ................................................ 83 Table 7-1 Table of Types of Constraint .......................................................................... 99 Table 9-1 Five common types of Subquery .................................................................. 120 Table 9-2 ALL and ANY Operator Combinations ....................................................... 122 Table 10-1 Four Types of Views .................................................................................. 131

xii

UNSW SISTM Lab Manual

Introduction to Oracle and Relational Database History of Oracle More than three decades ago, Larry Ellison and co-founders of Oracle Corporation, Bob Miner 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. Codd’s 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 Codd’s 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.

13

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 11g is 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 of down 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 lowcost 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 11g has 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.

14

UNSW SISTM Lab Manual

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 reverseengineering 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 an existing data model.

15

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

16

UNSW SISTM Lab Manual

The numbers in the diagram indicate the following: 1. A single row, record, or tuple representing all the data required to store for an employee. 2. A column or attribute containing the employee number. The employee number (employee_id) uniquely identifies an employee in the EMPLOYEE table. In this example, the employee number column is designated as the primary key. A primary key 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 the salaries of employees. 4. A column containing the department number, which is also a foreign key. A foreign key 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_id uniquely identifies a department in the departments table. 5. A field or data value can be found at the intersection of a row and a column. Each individual field can only have one value. 6. A field may have no value in it - this is called a null value. In the employees table, only those employees who have the role of sales representative have a value in the commission_pct (commission) field. The others have a null value.

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 To Be Covered SQL in Lab Week Statements

Data Manipulation Language (DML): Commands that modify data such as retrieving data from the databases, entering data, changing data and deleting data.

SELECT INSERT UPDATE DELETE

Transaction Control Language (TCL): COMMIT Commands that control transactional processing ROLLBACK in a database. SAVEPOINT Data Definition Language (DDL): CREATE Commands that define structures in a database, ALTER DROP such as create, alter and delete tables. RENAME Data Control Language (DCL): Commands that control access to rights the data GRANT REVOKE and tables in a database.

17

2, 3, 4, 5, 6, 8 and 9

8

7, 9 and 10

-

UNSW SISTM Lab Manual

Lab/Tutorial Arrangement (1) (2)

(3)

The tutor will start by demonstrating and discussing the lab materials. 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. 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.

18

UNSW SISTM Lab Manual

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 in Figure 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.

19

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-C’ to copy) or by clicking an icon on the menu.

20

UNSW SISTM Lab Manual

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 is located in the ‘Enter SQL Statement’ box 2. Run Script (F5): Execute all statements in the ‘Enter SQL Statement’ box by using the Script Runner 3. Autotrace (F6): Generate trace information for the statement 4. Execute Explain Plan (F10): Generate the execution plan, which you can see by clicking the Explain tab. 5. Commit (F11): Write any changes to the database and ends the transaction 6. Rollback (F12): Discard any changes to the database, without writing them to the database, and ends the transaction. 7. Unshared SQL Worksheet 8. Change Case: Change word to Uppercase, Lowercase or InitCap 9. Clear (Ctrl-D): Erase the statement or statements in the ‘Enter SQL Statement’ box 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 in Appendix 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.

1

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

21

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 user’s guide in Oracle SQL Developer User’s Guide (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 in Figure 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

22

UNSW SISTM Lab Manual

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 in Figure 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 in Figure 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 output – a script output – and, moreover, you can save the script output.

23

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 the two icons on the menu bar as shown in Figure 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 in Figure 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.

24

UNSW SISTM Lab Manual

Lab Week 2 Basic 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.1 Reference Casteel Chapter 2 2.1.2 Database 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 in Appendix A. 2.2.1 Selecting 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 All Data from 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

25

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

26

UNSW SISTM Lab Manual

2.3.2 Viewing Table Structure To list the column names of a table, you can use the command: DESC[RIBE] table_name [;] 2.3.2.1 Example: Find 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.3 Null Values Looking at the data structure of employees table as listed above (Figure 2-4), we can see there are three columns: (a) The Name column contains the column names of the employees table. (b) Null column indicates whether the column is allowable to have a NULL value. (c) Type describes 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 awarded for his examination, i.e. the examination mark column will have a Null value.

27

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 Number Number(n,m) CHAR(n)

Description Number without decimal Number with decimal Fixed length character string of length n characters VARCHAR2(n) Variable length character string of maximum length of n characters Date Date

Example Number (5) = 99999 Number(8,2) = 999999.99 Char(2) = “AB” VARCHAR(5) = “abc” Date = “01-JAN-2011”

Difference between CHAR(n) and VARCHAR2(n) The difference between CHAR(n) and VARCHAR2(n) is how a character is physically stored. 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.

28

UNSW SISTM Lab Manual

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 column_name_2 column_name_3 column_name_4 FROM employees;

AS New_Column_Heading_1, New_Column_Heading_2, “New Column Heading 3” AS “New Column Heading 4”

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 Alias Methods If you run the following query: SELECT employee_id employee_id last_name first_name FROM employees;

AS Employee, AS "Employee Id", Surname, "First Name"

The new column headings are displayed in Figure 2-5:

Figure 2-5 Demonstrate Four Common alias Methods

29

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 in Figure 2-7.

Figure 2-7 Using DISTINCT in the SELECT Statement

Figure 2-6 Not using Distinct in the SELECT Statement

30

UNSW SISTM Lab Manual

2.5.2 Use 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_id – returns 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_id – returns 28 records SELECT DISTINCT department_id, manager_id FROM employees; DEPARTMENT_ID ---------------------60 80 … 20 110 28 rows selected

MANAGER_ID ---------------------103 146 201 101

31

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 must be enclosed between single quotation marks (‘’) but not for numeric literals. SELECT column_name ||’Literal Strings’ || column_name FROM table_name; 2.6.1.1 Example: Using Concatenation and Literal Strings

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

32

UNSW SISTM Lab Manual

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, q’’ is for ‘s job id is as shown below (Figure 2-9):

Figure 2-9 Single Quotation Mark

33

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 Multiplication Division Addition Subtraction

* / + -

Order of Execution 1 2 3 4

SELECT column_name … FROM table_name; 2.7.1.1 Example: Arithmetic Operation Figure 2-10 shows all employees are given 10% pay rise and an extra $100 per month:

Figure 2-10 Arithmetic Operation

34

UNSW SISTM Lab Manual

Lab Week 3 Restricting 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.1 Reference Casteel Chapter 8 3.1.2 Database The 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.1 Numeric, 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 blob type can be used to store pictures. 3.2.1.1 Example: Numeric Values You can retrieve rows by specifying a specific numeric value:

Figure 3-1 SELECT - Numeric Column

35

UNSW SISTM Lab Manual

3.2.1.2 Example: Character Strings 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

36

UNSW SISTM Lab Manual

3.3 Logical Operators The three logical operators used to test in the condition are (examples based on Table 3-1):   

AND – both conditions must be true – o If A=B is true AND C=D is true, then the condition is true. OR – at least one condition must be true – o Either A=B is true OR C=D is true, then the condition is true. NOT – reverses of the ‘initial result’ – o If A=B is true, then NOT(A=B) becomes false Table 3-1 Logical Operators

Operators

AND

OR

Operator NOT

Condition

Result

A=B TRUE TRUE FALSE FALSE TRUE TRUE FALSE FALSE

C=D TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE

Condition A=B TRUE FALSE

Result FALSE TRUE

37

TRUE FALSE FALSE FALSE TRUE TRUE TRUE FALSE

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 in Table 3-1, Table 3-2 and Table 3-3.

38

UNSW SISTM Lab Manual

3.4.1.1 Example: Condition based on Numeric 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 on how you want to evaluate the values. Figure 3-5 and Figure 3-6 show different values are retrieved based on different operators. 10,000 and 11,000 were retrieved in Figure 3-6 but not in Figure 3-5. Alternatively, you can use BETWEEN ... AND ... operator. Values that are specified using the BETWEEN ... AND ... operator are considered as inclusive – thus, the results in Figure 3-6 and Figure 3-7 should be same.

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

39

UNSW SISTM Lab Manual

Figure 3-6 Condition is based on Inclusive Values

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

40

UNSW SISTM Lab Manual

3.4.1.2 Example: Condition based on Character Strings

Figure 3-8 Selecting based on Character Strings

Figure 3-9 Compare with Alphanumeric Values

41

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_code ‘M5V 2L7’, ‘YSW 9T2’, and ‘OX9 9ZB’ are among the selected records. This is because the ASCII decimal value for the number nine is 57, and, as an example, the ASCII decimal value for the letter ‘Y’ is 89 - since 89 is greater than 57, the records are selected as shown in Figure 3-10.

Figure 3-10 Demonstrate how the Values are selected based on the ASCII Code

You can select a range of character strings as shown in Figure 3-11. Alternatively, you can use the BETWEEN ... AND ... operator (see Figure 3-12) but you must specify the lower limit first. Otherwise, no record is retrieved as shown in Figure 3-13.

Figure 3-11 Select a range of Character String Values

42

UNSW SISTM Lab Manual

Figure 3-12 Select a range of Character String Values using BETWEEN ... AND ...

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

Figure 3-14 demonstrates the values for the character strings are case sensitive – ‘King’ is different from ‘KING’:

Figure 3-14 Demonstrate Case Sensitieve of Value Entered

43

UNSW SISTM Lab Manual

3.4.1.3 Example: Condition based on a Date Values Selecting using data values – must be in the format of ‘DD-MON-RR’. You can have ‘MAR’ or ‘Mar’ for the month component.

Figure 3-15 Month Component is not Case Sensitive

3.4.1.4 Example: The use of Not Equal or NOT Operator You can also use ‘not equal’ () or NOT operator in the condition:

Figure 3-16 The use of ‘’ (Not Equal) Operator

44

UNSW SISTM Lab Manual

Figure 3-17 The use of ‘NOT’ Operator

There are 107 employees but the two SELECT statements in Figure 3-17 only retrieved 106 employees - so one employee is missing? You can find the missing employee by testing a NULL condition because Jennie does not have a department_id (see Figure 3-18):

Figure 3-18 Testing a NULL value

45

UNSW SISTM Lab Manual

3.4.1.5 Example: The use of LIKE Operator You can use the LIKE operator to search for patterns: numbers, character strings and dates. The two wildcard characters used in the LIKE operator are: 

Percent sign (%): match any number of characters



Underscore sign (_): match exactly one character

Figure 3-19 Using LIKE operator

Figure 3-20 shows how the position of wildcard characters can change the results.

46

UNSW SISTM Lab Manual

Figure 3-20 Using Wildcard Characters in LIKE operator

Figure 3-21 shows an example of pattern matching on numbers and date values.

Figure 3-21 Pattern Matching on Numbers and Date Values

47

UNSW SISTM Lab Manual

3.4.2 Rules of Precedence The rules of precedence govern the order in which expressions in the SELECT statement are executed. The evaluation order: Table 3-4 Evaluation Order

1 2 3 4 5 6 7 8 9

Evaluation Order Arithmetic (*, /, +, -) operators Concatenation (||) operator Comparison (, =) conditions IS [NOT] NULL, LIKE, [NOT] IN [NOT] BETWEEN Not equal to NOT logical condition AND logical condition OR logical condition

However, the order of evaluation can be changed using parentheses. It is recommended that parentheses are used when an expression contains two or more operators. This way the intention of the developer is clear and ambiguity is avoided.

3.5 SELECT Statement When you want to sort an output, you have to use ORDER BY clause: SELECT FROM ORDER BY | [1, 2,…]; The rules related to the ORDER BY clause include: 

ORDER BY is the last clause in the SELECT statement



You can sort the list by ascending (ASC – default) or descending (DESC) order



You can sort by order number of the column in the SELECT list



You can sort a column that is not in the SELECT list



You can use NULLS FIRST OR NULLS LAST (default) for NULL values

The following queries will give you the same results – either sort by using the column or the order number of the column in the SELECT list: -- Sorted by column SELECT employee_id, last_name, first_name FROM employees ORDER BY last_name; /or/ 48

UNSW SISTM Lab Manual

-- Sorted by column number in the SELECT list SELECT employee_id, last_name, first_name FROM employees ORDER BY 2;

You are not recommended to use a column number when sorting because it might create a different result when you add or delete a column in the future without changing the column number. However, you will find automatic code generator such as in Oracle APEX uses column number in the ORDER BY clause. You can even sort a column that is not on the SELECT list. In the example below, the manager_id column is not listed in the SELECT clause: SELECT employee_id, last_name, hire_date FROM employees ORDER BY manager_id, hire_date;

3.5.1.1 Example: Sort by Numeric and Date Values

Figure 3-22 Sort by Numeric and Date Values

49

UNSW SISTM Lab Manual

Figure 3-23 Sort the Column in Descending Order

3.5.2 Sort NULL Values By default, the NULL values will appear If you want to have the NULL values to appear at the end of the list (Figure 3-24): at the beginning of the list, you have to use NULLS FIRST in the ORDER BY clause (Figure 3-25):

Figure 3-24 NULL Values appear End of the List

Figure 3-25 Using NULLS FIRST

50

UNSW SISTM Lab Manual

Lab Week 4 Selected Single-Row Functions 4.1 Objectives This week, you will learn some single-row SQL functions. There are many types of function in Oracle Database. A function accepts one or more arguments and then returns a single value. 4.1.1 Reference Casteel Chapter 10 4.1.2 Database The database used in this lab is HR database.

4.2 Overview of Functions Functions can be divided into the following types: Table 4-1 Type of Function

4.2.1 Case Conversion Functions The three case conversion functions in Oracle are: Table 4-2 Case Conversion Functions

Function LOWER UPPER INITCAP

Purpose Returns a string with all characters converted to lowercase Returns the string with all characters converted to uppercase Converts the first letter of every word to uppercase, and each subsequent letter to lowercase

51

Example LOWER(‘Oracle SQL’) becomes ‘oracle sql’ UPPER(‘Oracle SQL’) becomes ‘ORACLE SQL’ INITCAP(‘Oracle SQL’) becomes ‘Oracle Sql’

UNSW SISTM Lab Manual

4.2.1.1 Example: Case Conversion Function The case conversion function can be used to modify the way fields are displayed (Figure 4-1):

Figure 4-1 Examples of using Case Conversion Function

4.3 Character Manipulation Functions Character Manipulation Functions are used to find the length of a string, extract part of a string, or replace a character of a string. Some of the common functions are listed in the below table (Table 4-3), and more functions can be found in the Casteel. Table 4-3 Character Manipulation Functions Function SUBSTR

INSTR

LENGTH LPAD

RPAD

LTRIM

RTRIM REPLACE

Purpose Extract portion of a string SUBSTR(c, p, l): Where c is the character string p is the starting position of the character string l is the length of the string to be extracted Search a specified set of characters or a substring in a character string and returns the numeric position. Note: If no substring is found, then it will return a value of 0 (zero). The width of a character string. This function is used to pad or fill in the unoccupied blank area to the left of a character string with a specific character. LPAD(c, l, s): Where c is the character string l is total length to be displayed s is character used for padding This function is used to pad or fill in the unoccupied blank area to the right of a character string with a specific character. This function removes all occurances of a given string from the of a given string LTRIM(c, s): where c is the character string s is substring to be removed (if omitted this parameter defaults to the space character) As for LTRIM but this function removes a substring from the right side of a character string. Substitutes a string with another specified string

52

Example SUBSTR(‘Hello World’, 1, 5) returns Hello SUBSTR(‘Hello World’, -5, 5) returns World (minus in -5 means count from the end of the string) INSTR(‘Hello World’, ‘W’) returns 7

LENGTH(‘Hello World’) returns 11 LPAD(‘Hello World’, 15, ‘*’) returns ****Hello World

RPAD(‘Hello World’, 15, ‘*’) returns Hello World**** LTRIM(‘ Hello World’) returns ‘Hello World) LTRIM(‘Hello World’, ‘Hello’) returns ‘ World’ (note: the space before the word World was not removed) RTRIM(‘Hello World’, ‘World’) returns Hello REPLACE(‘Hello World’, ‘Hell’, ‘G’) returns Go World

UNSW SISTM Lab Manual

4.3.1.1 Example: Character Manipulation Functions Figure 4-2 shows an example of using Character Manipulation Functions.

Figure 4-2 An example of using Character Manipulation Functions

Note: in Oracle SQL, the position of a string starts from one (1) and not zero (0).

4.4 Number Functions We will first examine some of the common number functions (Table 4-4) follow by some examples. Table 4-4 Table of Common Number Functions

Function Purpose ROUND

The Round function is used to round numeric fields to the stated precision.

TRUNC

The TRUNC function is used to round numeric fields to the stated precision.

MOD

The MOD (modulus) function returns the remainder of a division operation.

ABS

The ABS (absolute) function returns a positive numeric value.

POWER

The POWER function is used to calculate a statistical power.

53

UNSW SISTM Lab Manual

4.4.1.1 Example: Examples of using Number Functions

Figure 4-3 Examples of using ROUND and TRUNC Functions

Figure 4-4 Examples of using ABS and POWER Functions

4.4.2 The Dual Table The dual table is a public ‘dummy’ table available in the Oracle database. It has one column called dummy with a value ‘X’. We do not use the value but use the table as a ‘dummy’ to do calculation like in Figure 4-4, or find today’s date: SELECT sysdate FROM dual; SYSDATE --------11-FEB-11

54

UNSW SISTM Lab Manual

4.5 Date Functions Handling dates is not an easy task. Some global organisations have systems that are used across different countries and timezones where the date format may differ in each country. For instance, in Australia, the default format for dates is dd-mm-yyyy (e.g. 1801-2011) whereas in the United States, the format is mm-dd-yyyy (e.g. 01-18-2011). Oracle databases can handle the different date formats used in different countries. The default format of date in Oracle database is DD-MON-RR. The textbook mentions DD-MON-YY format. The difference between RR and YY is the way dates around the turn of the millennium are dealt with (19 for YY and 20 for RR). In this course, we only use DD-MON-RR. The textbook Casteel has a very good introduction to the date functions, so you are encouraged to read this section. In the lab, we only cover a few of these functions. For today’s date, you are recommended to use SYSDATE and not CURRENT_DATE.

4.5.1.1 Example: Date Function An example of using DATE function is to calculate how many years (approx.) the employees have been working in the company.

Figure 4-5 Example of using DATE function

4.6 Regular Expressions We will not cover this topic in the lab but it is covered in Casteel (pp. 357-359).

55

UNSW SISTM Lab Manual

4.7 Other Functions There are other functions which are commonly used are listed in Table 4-5. Table 4-5 Table of Common Other Functions Function

Purpose

Example

NVL

You may want to substitute a value for any NULLs encountered. For instance, a number multiplied by a NULL value is NULL and this may not be what you want. This function is used to address a column when it has a NULL value. For instance, you might want to substitute a NULL value with zero.

Figure 4-6

NVL2

This function takes three parameters: x, y and z. The function will return y if x is not NULL. If x is NULL z will be returned instead.

Figure 4-7

NULLIF

This function is used to compare two values for equality – if the two values are equal, then it will return a NULL value.

Figure 4-8

TO_CHAR

You will use this function frequently to format values. For instance, this function can be used to convert dates and numbers to a formatted character string.

Figure 4-9

TO_NUMBER

This function is used to convert a character string to a number.

SOUNDEX

SOUNDEX function is to search for value based on the pronunciation of words rather than search for value based on an exact character string.

56

Figure 4-10

UNSW SISTM Lab Manual

4.7.1.1 Example: Using NVL Functions

Figure 4-6 Using NVL Function

Figure 4-7 Example of NVL2 Function

57

UNSW SISTM Lab Manual

Figure 4-8 Example of using NULLIF and NULLS FIRST

NOTE: We have not covered the JOIN statements yet, so do not worry if you do not understand some of the examples in Casteel.

Figure 4-9 Examples of using TO_CHAR

58

UNSW SISTM Lab Manual

Figure 4-10 Example of using SOUNDEX

4.8 CASE Expression The CASE expression allows you to specify different actions depending on the value. You can test a number of conditions at the same time and if none of the conditions are true, then it will assign a default value in the ELSE clause. The syntax of CASE expression is:

SELECT column_name, … CASE WHEN (condition 1) WHEN (condition 2) ELSE END column_alias FROM table_name [WHERE …]

THEN THEN

Note: The DECODE statement is a proprietor function of Oracle. This function provides similar functionality to CASE statement. The recommendation from Oracle is to use CASE statement, and change the DECODE statement to CASE statement where possible.

59

UNSW SISTM Lab Manual

An example of setting the salary level based on salary (Figure 4-11):

Figure 4-11 An example of using CASE statement

60

UNSW SISTM Lab Manual

Lab Week 5 Joining Data from Multiple Tables 5.1 Objectives This week, you will learn how to join two or more tables. You will be able to identify a Cartesian join; create equality and non-equality joins; create a self-join; and distinguish an inner join from an outer join. In addition, the theoretical principles behind the development of SQL statements using the relational algebra from Codd’s original paper will be discussed. 5.1.1 Reference Casteel Chapter 9 5.1.2 Database The database used in this lab is HR database.

5.2 Relational Algebra So far, you have learned how to use SQL statements to retrieve data. Before we continue discussing more SQL statements, we will first have a look at the theoretical principles behind the development of these SQL statements. The SQL statements were first developed based on relational algebra from Codd’s original paper. Relational algebra is a high-level procedural language, which consists of a collection of operators. Of course, since Codd’s original definition2 of eight operators, more operators, and combination of operators have been added. The eight operators are defined and explained in Table 5-1:

2

Date, C. J., 1995, An Introduction to Database Systems, 6th Edition, Addison-Wesley Publishing, USA, p. 141

61

UNSW SISTM Lab Manual

Table 5-1 Definition of Algebra Operators

Operator Union

Definition Union returns a relation consisting of all tuples appearing in either or both of the relations, i.e., select all rows from both tables (A ∪ B). A

Intersect returns a relation consisting of all tuples appearing in both of the relations, i.e. select only the common rows from both tables. A

Difference returns a relation consisting of all tuples appearing in the first and not the second of two specified relations, i.e. select rows that are in the first table but not in the second table. Note: A – B is different from B – A.

A

(A-B) B

A

A s1 s2

A∪B s1 s2 s3 s4

A∩ B s2

B s3 s2

B

Difference

A s1 s2 B s3 s4

B

Intersect

Example

A s1 s2 B s3 s2

(B-A) B

62

A- B s1 B- A s3

UNSW SISTM Lab Manual

Operator Restrict

Definition

Example

Restrict returns a relation consisting of all tuples from a specified relation that satisfy a specified condition, i.e. rows are selected based on a condition(s) using a WHERE clause.

A s1 s2

Project

It returns a relation consisting of all tuples that remain as (sub)tuples in a specified relation after specified attributes have been eliminated, i.e. select a column(s) from a table.

col A col B a1 b1 a2 b2

Cartesian Product

It returns a relation consisting of all possible tuples that are a combination of two tuples, one from each of two specified relations, i.e. rows in the first table TIMES rows in the second table.

WHERE A = 's2' s2

A s1 s2 B b1 b2

63

SELECT col A a1 a2

A TIMES B s1 b1 s1 b2 s2 b1 s2 b2

UNSW SISTM Lab Manual

Operator Natural Join

Definition Natural join returns a relation consisting of all possible tuples that are a combination of two tuples, one specified from each of two specified relations, such that the two tuples contributing to any given combination have a common value for the common attributes(s) of the two relations.

Example

A c1 a1 a2

c2 b1 b2

B c1 a1 a2 Divide

Takes two relations, one binary and one unary, and returns a relation consisting of all values of one attribute of the binary relation that match (in the other attribute) all values in the unary relation.

64

c3 c1 c2

A c1 a1 a1 a1 a1 a2 a3 a3 a3

A JOIN B c1 c2 c3 a1 b1 c1 a2 b2 c2

c2 b1 b2 b3 b4 b1 b1 b2 b3

B c2 b1 b3 A Divided by B c1 a1 a3

UNSW SISTM Lab Manual

Now, you should have a better understanding of the theoretical background behind the development of SQL statements of what you have already learned, and what you will learn in the next few chapters.

5.3 Purpose of Joins Joins are used to link tables and reconstruct data in a relational database. Joins can be created using: o Conditions in a WHERE clause (Traditional Join Method) or o JOIN in the FROM clause (ANSI JOIN Method) 5.3.1 Cartesian Joins Cartesian Joins are created by omitting joining condition in the WHERE clause or through CROSS JOIN keywords in the FROM clause. This creates a result of every possible row combination (m*n) as shown in Figure 5-1.

Figure 5-1 Cartesian Joins

Normally, when people see a join such as the one shown in Figure 5-1, they will assume it is incorrect. If you want to use a Cartesian join, it is recommended that you use the CROSS JOIN clause to indicate to other people your intention: SELECT * FROM regions CROSS JOIN countries;

65

UNSW SISTM Lab Manual

5.4 Using Alias for Tables If a column occurs in both tables, you must specify which table the column is referred to. Otherwise, an error or similar message will appear: -- SQL Error: ORA-00918: column ambiguously defined -- 00918. 00000 - “column ambiguously defined”

If, for example, the department_id column is in both employees and departments tables, you can refer department_id in the employees table as ‘employees.department_id’ and department_id in the departments table as ‘departments.department_id’. Your SELECT statement will look like this: SELECT employees.last_name, employees.department_id, departments.department_name FROM employees, departments WHERE employees.department_id = departments.department_id;

Alternatively, instead of using the full table name, you can define aliases for your tables. It is a good practice to identify all the tables using aliases. In this way, you can associate the columns with the tables. It will also help to improve the performance when running the query - the table alias give a table a shorter name - it keeps the SQL code smaller, more readable and uses less memory. Using alias for the above example, your new SELECT statement will look like this: SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id = d.department_id;

When using an alias, it is good practice to have a meaningful identification so it is easy for other people to indentify the tables. The first letter of the table’s name is frequently used as an alias. Using random letters like ‘a, b, c’ to indentify your tables might be confusing and is not recommended: SELECT a.last_name, a.department_id, b.department_name FROM employees a, departments b WHERE a.department_id = b.department_id;

66

UNSW SISTM Lab Manual

5.5 Traditional Join Method versus ANSI JOIN Method The SELECT statement in previous section is known as traditional join method because two tables are linked through specifying their columns in the WHERE clause. Traditional joins are still embedded in most of the older queries and computer programs. Most of the older generation of IT personnel do not like, or resist, to change to the ANSI JOIN method because they have been using for years (like ‘teaching an old dog new trick’). The ANSI JOIN method was introduced for the purpose of resolving some of ambiguities and reducing errors by forcing you to specify the columns in the JOIN statement. It is usually difficult to find the error when there are a few tables linked in the WHERE clause. If, for example, you accidentally forget to enter the condition to test for location_id, the query will still run and 2,438 rows, instead of 106 rows, will be retrieved. SELECT e.last_name, e.department_id, d.department_name, l.city FROM employees e, departments d, locations l WHERE e.department_id = d.department_id -- Missing: AND d.location_id = l.location_id ;

On the other hand, you will get an error if the condition statement is not entered in the JOIN statement. Thus, this will force you to enter a condition: SELECT e.last_name, e.department_id, d.department_name, l.city FROM employees e JOIN departments d ON e.department_id = d.department_id JOIN locations l -- Missing: ON d.location_id = l.location_id ;

Next, we will introduce and discuss the JOIN statements.

67

UNSW SISTM Lab Manual

5.6 Equality Joins You can link rows through equivalent data that exists in both tables. This is created through creating equivalency condition in the WHERE clause and using NATURAL JOIN, JOIN…USING, or JOIN…ON keywords in the FROM clause. 5.6.1 NATURAL JOIN Clause The NATURAL JOIN clause is used to link two tables based on the same column name. 5.6.1.1 Example: Using NATURAL JOIN

Figure 5-2 Using NATUAL JOIN

Using NATURAL JOIN in Figure 5-2 is fine because there is only one common column, namely location_id, between the two tables. However, when there are two or more columns with the same name in both tables, Oracle will select and link the tables using one of the common columns. This automatic linking may not produce the join you after, Oracle may not choose the common column you intended to link the two tables.

68

UNSW SISTM Lab Manual

For example, if you want to link employees and departments table using NATURAL JOIN, Oracle will use manager_id instead of department_id to link the two tables even when department_id is a foreign key in the employees table and primary key in the departments table (see Figure 5-3):

Figure 5-3 NATURAL JOIN using manager_id

69

UNSW SISTM Lab Manual

5.6.2 JOIN … USING Clause As shown in Figure 5-3, NATURAL JOIN can be problematic if there are two or more columns common to both tables. To resolve this ambiguity, you can specify the column you want to link. In Figure 5-4, we specify joining the two tables using department_id column. Please note that there are 106 records in Figure 5-4 but only 32 records in Figure 5-3.

Figure 5-4 An Example using JOIN ... USING clause

You should not use any prefix alias in the USING clause because department_id is common to both tables otherwise an error message will appear. For example, in Figure 5-5, department_id does not have the alias ‘d’ links to the column.

70

UNSW SISTM Lab Manual

5.6.2.1 Example: JOIN … USING Clause with Alias

Figure 5-5 JOIN … USING clause with alias

5.6.3 JOIN … ON Clause Alternatively, you can use JOIN … ON … clause to specify columns to join. The previous example (Figure 5-5) can be modified to use the JOIN … ON … clause (Figure 5-6), and it will still produce the same result. The way the links are defined in the JOIN … ON … clause is very similar to the Traditional Join Method. 5.6.3.1 Example: JOIN … ON Clause

Figure 5-6 JOIN … ON Clause 71

UNSW SISTM Lab Manual

You can join three or more tables using JOIN … ON clause as shown in Figure 5-7. You can still get the same result using JOIN … USING clause as shown in Figure 5-8.

Figure 5-7 Using JOIN ... ON ... for Three tables

Figure 5-8 Using JOIN ... USING ... for Three tables

72

UNSW SISTM Lab Manual

5.7 Non-equality Joins A non-equality join is when you use any other comparison operators other than the equal sign in the WHERE clause. Another instance is when you use JOIN…ON clause in the FROM clause for a non-equivalent condition as shown in Figure 5-9.

Figure 5-9 An Example of Non-equality Join

73

UNSW SISTM Lab Manual

5.8 Self-Joins Self-join is to link a table to itself - for example, link employees table to employees table. Thus, it requires the use of table aliases and use of a column qualifier. 5.8.1.1 Example: Self-Joins A manager of an employee is also an employee of the company. If you want to find the manager’s name of an employee, you have to link the employees table back to the employees table to get the name of an employee’s manager.

Figure 5-10 An Example of self-joins

5.8.2 INNER JOINS Although we only use the word JOIN, with the equality, non-equality, and self-joins discussed so far, they are actually all classified as INNER JOINS. An inner join (sometimes called a simple join) is a join of two or more tables that returns only those rows that satisfy the join condition.

5.9 OUTER JOINS On the other hand, you use outer joins to include rows that do not have a match in the other table. You can think of the outer join as an optional link with another table. There are three types of OUTER JOINS: FULL, LEFT, or RIGHT. 5.9.1 Difference between INNER and OUTER Joins In summary, joining of two tables returns only the matching rows is called an INNER join. On the other hand, a join between two tables returning all the matching rows of an INNER join as well as any unmatched rows from the left table, or from right table, or both tables is called a LEFT, or a RIGHT, or an OUTER join respectively. This is the way to retrieve the NULL records. 74

UNSW SISTM Lab Manual

5.9.2 LEFT OUTER JOIN With a LEFT OUTER JOIN, if the table listed on the left side of the join has an unmatched record, it will theoretically match with a NULL record. 5.9.2.1 Example: Using LEFT OUTER JOINS Figure 5-11 shows the employee King has not got a manager because King is the president of the company. All other employees have a manager. If you do not use a LEFT OUTER Join, the record of employee King will not be retrieved.

Figure 5-11 Using LEFT OUTER JOINS

75

UNSW SISTM Lab Manual

5.9.3 RIGHT OUTER JOIN The same can be applied to RIGHT OUTER JOIN. All the NULL records of the table on the right hand side of the JOIN can be retrieved. 5.9.3.1 Example: RIGHT OUTER JOIN Figure 5-12 shows employee 101 has worked as AC_ACCOUNT and AC_MGR, and he is now an AD_VP of the company. Other employees such as 103, 104 and 105 have not changed their job as IT_PROG since joining the company – these records are retrieved using RIGHT OUTER JOIN.

Figure 5-12 An Example of using RIGHT OUTER JOIN

5.9.4 FULL JOIN FULL JOIN will return records from both tables even the ones that do not have a matching record in the other table.

76

UNSW SISTM Lab Manual

5.10 SET OPERATORS Set operators are used to combine the results of two (or more) SELECT statements. Valid set operators are UNION, UNION ALL, INTERSECT and MINUS. Table 5-2 Desription of the Set Operators

5.10.1 UNION The UNION operator returns all the rows from multiple tables and eliminates any duplicate rows to both queries. 5.10.1.1 Example: UNION You can see the records retrieved from job_history table have ‘…’ as the last_name whereas records retrieved from employees display the last_name of the employee.

Figure 5-13 An Example using UNION operator

77

UNSW SISTM Lab Manual

The number of columns in the SELCT statement determines the number of rows to be retrieved. For instance, if we get rid job_id and department_id columns, then the result is different for employee_id 101 (see Figure 5-14).

Figure 5-14 Using UNION operator with two columns removed

5.10.2 UNION ALL The UNION ALL operator returns all rows from both queries in a single result set. 5.10.3 INTERSECT The INTERSECT operator returns only those records with the same values in the selected columns in both tables. For instance, you want to find employees who went back to one of their previous jobs (Figure 5-15). However, in Figure 5-16, it shows that employee 200 (Jennifer Whalen) went back to her old job but works in a different department.

78

UNSW SISTM Lab Manual

Figure 5-15 An Example of using INTERSECT Operator

Figure 5-16 Another Example of using INTERSECT Operator

79

UNSW SISTM Lab Manual

5.10.4 MINUS The MINUS operator returns all the rows selected by the first query but not in the second query. For example, Figure 5-17 shows employees have not changed their job since joining the company.

Figure 5-17 An Example using MINUS Operator

80

UNSW SISTM Lab Manual

Lab Week 6 Group Functions 6.1 Objectives This week, you will learn group functions, also known as multiple-row functions. These functions will return one result per group. The multiple-row functions covered include SUM, AVG, MIN and MAX. You will learn to use the COUNT function to return records containing non-NULL values, or records containing NULL values. We will also cover the GROUP BY and HAVING clauses. In this course, we will not cover the topic on multidimensional analysis – GROUPING SETS, CUBE, and ROLLUP functions. 6.1.1 Reference Casteel Chapter 11 6.1.2 Database The database used in this lab is HR database.

6.2 Understand Grouping We will first discuss briefly how the grouping and group functions work in this section, and in the next section, we will demonstrate using SQL statements. So far, individual records are retrieved and displayed using SQL statements. However, you might want to find the average mark of the students of a particular course. In this case, you need to use the group functions. Grouping is to group a number of rows based on a predefined or defined category. In our demonstration, we have two group of students – Group 13 and 14 – each group has 4 students and their marks are shown in Table 6-1. Table 6-1 Group 13 and 14

Name G13A G13B G13C G13D G14A G14B G14C G14D

Group 13 13 13 13 14 14 14 14

81

Marks 2.00 4.00 6.00 8.00 1.00 3.00 5.00 7.00

UNSW SISTM Lab Manual

If you want to find an average mark for all students, you just have to average all the marks (average mark is 4.50) as shown in Table 6-2. Table 6-2 Average Mark for all students

Name G13A G13B G13C G13D G14A G14B G14C G14D

Marks 2.00 4.00 6.00 8.00 1.00 3.00 5.00 7.00

Average:

4.50

If you want find out the average mark for each of the groups, namely Group 13 and 14, you have to use the GROUP BY clause. The GROUP BY clause will report the group average at the level as specified. In this case, the group average for Group 13 and 14 are shown in Table 6-3. Table 6-3 Average at Group Level

Name G13A G13B G13C G13D Group 13 G14A G14B G14C G14D Group 14

Group By Marks Average 2.00 4.00 6.00 8.00 5.00 1.00 3.00 5.00 7.00 4.00

Group 13 13 13 13 14 14 14 14

If you want to select the data, you can use the WHERE clause. However, if you want to select the data at the group level, you have to use the HAVING clause. We now go through the WHERE clause, HAVING clause, and using both the WHERE and HAVING clauses. If you only want to find an average mark for student’s individual mark >= 5, the rows for marks >= 5 will be selected first, and then the marks for these selected rows will be 82

UNSW SISTM Lab Manual

averaged. In Table 6-4, he marks for G13A, G13B, G14A and G14B are not selected because they are less than 5. On the other hand, if you are using the HAVING clause (you must use GROUP BY when using HAVING clause), the marks will be averaged at the group level, and groups with an average mark greater than 5 are then selected, In this case, only Group 13 is selected as shown in Table 6-4. Table 6-4 Finding the average mark with WHERE clause and HAVING clause

Name G13A G13B G13C G13D G14A G14B G14C G14D Average

Group Marks 13 2.00 13 4.00 13 6.00 13 8.00 14 14 14 14

1.00 3.00 5.00 7.00

WHERE clause WHERE Marks >= 5 Marks Average No No Yes 6.00 Yes 8.00 No No Yes Yes

5.00 7.00

HAVING clause HAVING GROUP Average(Marks) BY Marks Average >= 5 2.00 4.00 6.00 8.00 Group 13 5.00 Yes 1.00 3.00 5.00 7.00 Group 14 4.00 No

6.50

When using both the WHERE and HAVING clauses, the order of selection is as follows. First, using Table 6-5 as an example, WHERE clause is applied, so only rows with marks >= 5 are selected. The average mark for Group 13 and 14 is 7.00 and 6.00 respectively. Second, HAVING clause is applied for average mark greater than 7.00, and in this case, only Group 13 is selected. Table 6-5 Using WHERE Clause and HAVING Clause

WHERE Clause and HAVING Clause GROUP WHERE Name Group BY Marks Marks >= 5 G13A 13 2.00 No G13B 13 4.00 No G13C 13 6.00 Yes G13D 13 8.00 Yes Group 13 Group 13 G14A 14 1.00 No G14B 14 3.00 No G14C 14 5.00 Yes G14D 14 7.00 Yes Group 14 Group 14 83

Marks

HAVING Average(Marks) Average >= 7

6.00 8.00 7.00

Yes

6.00

No

5.00 7.00

UNSW SISTM Lab Manual

6.3 SELECT Statement The function is used to group data. The SELECT statement is defined as follows: SELECT column_name, group_function(column) FROM table [WHERE condition] [GROUP BY group_by_expression] [HAVING group_function(column) condition] [ORDER BY column_name];

The rules of the statement: 

the data will be summarised and reported at the group level



it cannot reference column aliases

6.3.1 Group Functions The group functions include SUM, AVG, MIN and MAX:    

SUM function is used to calculate the total amount of a column for a group of rows AVG function is used to calculate the average values of a column MIN function returns the smallest value MAX function returns the largest value

6.3.1.1 Example: Group Functions

Figure 6-1 An Example of using Group Functions

84

UNSW SISTM Lab Manual

6.3.2 Other Data Types Other than numeric value, you can use group functions for date values and character strings. 6.3.2.1 Example: Date Values Figure 6-2 shows you can use MIN and MAX functions to manipulate date values.

Figure 6-2 Find Minimum and Maximum Date Values

Note: there are other group functions such as STDDEV and VARIANCE which you can find in the Casteel. 6.3.3 COUNT COUNT function serves two purposes: 

Count non-NULL values and



Count total records, including those with NULL values

6.3.3.1 Example: Using COUNT If we need to count values excluding NULL values, we need to use DISTINCT with the COUNT function. Otherwise, you can use COUNT(*) to count the all values including NULL values.

Figure 6-3 Count non-NULL values

85

UNSW SISTM Lab Manual

Figure 6-4 Count NULL values

6.3.3.2 Example: Handling NULL Values You can use operator such as NVL to handle the NULL values in the column calculation. Figure 6-5 demonstrates how NULL values can be handled. The average commission paid for 45 employees is $1,614. However, in the second query, it shows 34 employees received an average of $2,316 in commissions, and 11 employees did not receive any commissions.

Figure 6-5 An Example of Handling NULL values

86

UNSW SISTM Lab Manual

6.3.4 Grouping Data When you need a sub-total at the group level, you need to use a GROUP BY clause.

6.3.4.1 Example: GROUP BY In Figure 6-6, the calculations are done at the group level, in this case the column of department_id. If you want a total for all the groups, you need to write another SELECT statement as shown in Figure 6-7.

Figure 6-6 An Example of using GROUP BY

Figure 6-7 Total of All Records

87

UNSW SISTM Lab Manual

6.3.4.2 Example: GROUP BY, ORDER BY, WHERE and HAVING You can use WHERE clause to select data values when using a GROUP BY clause as shown in Figure 6-8. If you want to select the output at the group level, you have to use the HAVING clause as shown in Figure 6-9. The average salary for departments 80 and 100 is less than $10,000. Therefore, they are not selected.

Figure 6-8 An Example of using GROUP BY and WHERE Clauses

Figure 6-9 An Example of using GROUP BY and HAVING Clauses

You will get an error if you do not include group functions such as AVG() in the HAVING clause. HAVING clause is associated with GROUP BY clause, and you must have a GROUP BY clause if you want to use HAVING. Thus, HAVING clause is to test the condition at the group level. When sorting a column or columns, you must use ORDER BY. GROUP BY does not guarantee the result set to be sorted as you might want.

88

UNSW SISTM Lab Manual

6.3.4.3 Example: Complex Queries You can have complex queries by joining a number of tables before applying a GROUP BY/HAVING clause as shown in Figure 6-10. It is a good idea to include description of the shown IDs. In this case, we include both department id and department name.

Figure 6-10 An Example of Complex Queries

You can also group a number of columns in the GROUP BY clause. In the below example, Figure 6-11, we group country_id and department_id. Please note there are seven departments under country US.

Figure 6-11 An Example of Complex Group By

89

UNSW SISTM Lab Manual

If we apply HAVING clause to the query in Figure 6-11 by selecting only the average salary greater than $5,000, three of the US departments will be discarded as shown in Figure 6-12. The HAVING clause applies to the combination of the columns in the GROUP BY clause.

Figure 6-12 An Example of Complex GROUP BY/HAVING

90

UNSW SISTM Lab Manual

Lab Week 7 Table Creation, Constraints and Management 7.1 Objectives So far, you have been using predefined tables. Today, you will learn to create new tables, and also learn how to use a subquery to create a new table using Data Definition Language (DDL). You will also learn to add constraints to tables. You will be able to distinguish among PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, and NOT NULL constraints and the appropriate use for each constraint. You will gain the knowledge to create constraints at the column level and table level. Apart from creating a new table, you will learn to add a column to an existing table; modify the definition of a column in an existing table; and delete a column from an existing table. In addition, you will find out how to mark a column as unused and delete it at a later time; rename a table; and delete a table from the database. 7.1.1 Reference Casteel Chapter 3 and 4 7.1.2 Database The database used in this lab is HR database.

7.2 CREATE TABLE Statement The syntax for CREATE table: CREATE TABLE [schema.]table_name (column_name datatype [DEFAULT expression], [...]); Requirements:  

You must have a CREATE TABLE privilege Allow to access to a storage area

Table and column names:        

Can contain a maximum 30 characters – no blank spaces Must begin with a letter Can contain numbers, underscore (_), and number sign (#) Must be unique No reserved words are allowed Column definition list must be enclosed in parentheses Datatype must be specified for each column Maximum of 1,000 columns per table

91

UNSW SISTM Lab Manual

7.2.1.1 Example: CREATE a TABLE We create a new table called departments_history to keep track changes of department name.

Figure 7-1 CREATE a new table

In the Oracle SQL Developer, you have to click on the ‘refresh’ option to see your new table. A data dictionary is a typical component of a DBMS that maintains information about database objects. You can query the data dictionary to verify all the tables that exist in your schema. There are options in the Oracle SQL Developer which you can perform these tasks – your tutor will show you some of the options which you might useful for your lab exercises:

Figure 7-2 Oracle SQL Developer Layout 92

UNSW SISTM Lab Manual

7.2.2 User Tables In Oracle database, there are tables which are created by you, and system tables created by Oracle - a good example is the DUAL table. You can use some of these public tables. A public table called user_tables has the information of all the tables created by you: -- List all the tables in your database. SELECT table_name FROM user_tables; TABLE_NAME -----------------------------REGIONS LOCATIONS DEPARTMENTS JOBS EMPLOYEES JOB_HISTORY DEPARTMENTS_HISTORY COUNTRIES 8 rows selected

7.3 CREATE TABLE … AS … Statement Instead of defining columns when creating a table, you can create a table based on the results of a query, allowing you to, for instance, easily copy the structure of another table. Not only you will copy the data structure and, by default, you will also copy the data and some of the constraints of that table. You can also add new columns as part of the creating process. CREATE TABLE table_name [column_name] AS (subquery); 7.3.1.1 Example: CREATE TABLE … AS …

Figure 7-3 CREATE TABLE … AS …

93

UNSW SISTM Lab Manual

7.4 Modifying An Existing Table You can use the ALTER TABLE command to modify an existing table:   

Use an ADD clause to add a column Use a MODIFY clause to change a column Use a DROP COLUMN to drop a column

ALTER TABLE table_name ADD | MODIFY | DROP COLUMN | column_name [definition]; The modification guidelines:  Column must be as wide as the data it already contains  If a NUMBER column already contains data, you cannot decrease size of that column  Adding or changing default data does not affect existing data 7.4.1.1 Example: ALTER TABLE – Add, Modify and Drop

Figure 7-4 ALTER TABLE – Add, Modify and Drop

94

UNSW SISTM Lab Manual

7.5 ALTER TABLE…SET UNUSED (and DROP) Statement Instead of dropping a column which immediately taken effect, you might want to mark a column for deletion. Please note that once a column is marked for deletion, it cannot be restored but storage space can be freed at a later time. One of the reasons you might want to mark a column for deletion now, and later delete permanently is that, during the peak period of a working day, the table might be used by many applications, and deleting a column of a table requires locking the table. Locking the whole table exclusively might prevent some applications from running. Additionally, system resources may be tied up unnecessarily. The syntax for the ALTER TABLE is: ALTER TABLE table_name SET UNUSED [COLUMN] column_name; To free up storage space from columns previously marked as unused: ALTER TABLE table_name DROP UNUSED COLUMNS;

95

UNSW SISTM Lab Manual

7.5.1.1 Example: ALTER TABLE … SET UNUNSED and DROP

Figure 7-5 ALTER TABLE … SET UNUNSED and DROP

7.6 Renaming a Table This statement is used to rename a table: RENAME table_name TO new_table_name For example, -- Before renaming the table SELECT table_name FROM USER_TABLES; TABLE_NAME -----------------------------REGIONS … JOB_HISTORY DEPARTMENTS_HISTORY EMPLOYEES_HISTORY COUNTRIES …

96

UNSW SISTM Lab Manual

-- Rename a table... RENAME employees_history TO employees_hist_2011; -- employees_history table is not longer recognised DESCRIBE employees_history; DESCRIBE employees_history ERROR: ---------------------------------------------ERROR: object EMPLOYEES_HISTORY does not exist …

SELECT table_name FROM USER_TABLES; TABLE_NAME -----------------------------REGIONS … JOB_HISTORY DEPARTMENTS_HISTORY EMPLOYEES_HIST_2011 COUNTRIES

7.7 Truncating a Table TRUNCATE TABLE command is when rows in the table are deleted but the structure of table remains, i.e. clear the data of a table but keep its table structure. Note: this is different from the TRUNC() function. TRUNCATE TABLE table_name

7.8 Deleting a Table DROP TABLE is to delete a table including its structure and contents. DROP TABLE table_name [PURGE]

Oracle 10g has introduced a recycle bin. You can drop a table and their contents, but, later on, you can recover the table from the recycle bin – it functions like the recycle bin in Windows. -- Delete a table DROP TABLE employees_hist_2011; DROP TABLE employees_hist_2011 succeeded.

97

UNSW SISTM Lab Manual

-- Find the deleted table in the recycle bin SELECT object_name, original_name FROM recyclebin; OBJECT_NAME ORIGINAL_NAME ------------------------------ -------------------------------BIN$0Xud4LLjRL2rhSXQejW1zg==$0 EMPLOYEES_HIST_2011

If you want to recover the table from the recycle bin, you have to use the FLASHBACK command: FLASHBACK TABLE table_name TO BEFORE DROP -- Recover the table from the recycle bin FLASHBACK TABLE employees_hist_2011 TO BEFORE DROP FLASHBACK TABLE succeeded.

If you want to delete the table permanently, you have to delete the table (again!) in the recycle bin using the PURGE TABLE command. -- To remove the table permanently from the recycle bin PURGE TABLE “BIN$0Xud4LLjRL2rhSXQejW1zg==$0” [Note: the object name is uniquely created and your object name will be different from this example.]

Alternatively, you could have deleted the table permanently in the first place – you just have to add the PURGE keyword to the DROP TABLE statement: DROP TABLE employees_hist_2011 PURGE

7.9 Constraints Up to this point, we have been defining how to create, modify and delete a table. Next, you have to define constraints in your tables. Constraints can be defined as: 

Rules used to enforce business rules, practices, and policies



Rules used to ensure accuracy and integrity of data

Constraints can be created at the column level by including the constraint as part of the column definition or at the table level by defining the constraint after all columns have been defined. When created at the column level, the column that is the objective of the constraint is identified first, and then the constraint information is provided.

98

UNSW SISTM Lab Manual

All constraints are enforced at the table level and if a data value violates a constraint, the entire row is rejected. The description for the five constraint types are as follows: Table 7-1 Table of Types of Constraint

If the constraints are created using the table level approach, the type of constraint is identified first, and then the column. A constraint can be assigned a name when it is created; otherwise, the Oracle server will assign a name for the constraint using the convention format SYS_Cn , e.g. employee_id_pk (see Casteel p.101). When constraint violations occur, the naming convention for constraint names will help to quickly identify the specific problem. 7.9.1 Create Constraints If you want to create a constraint at the same time you are creating a table, you need to define the constraint after the column: CREATE TABLE table_name column_name [CONSTRAINT constraint_name] constraint_type [, column_name]

Alternatively, if you want to add a constraint after a table is created, you have to use the ALTER TABLE command: ALTER TABLE table_name ADD [CONSTRAINT constraint_name] constraint_type column_name; 99

UNSW SISTM Lab Manual

7.9.2 Create a Table with Constraints You can create a primary key as part of the CREATE table process or the primary key can be added after the table has been created. A primary key can consist of one column, or two or more columns. 7.9.2.1 Example: Primary and Foreign Keys in the Statement

Figure 7-6 Create a New Table with Constraints

If you enter an invalid country_id, then an error message containing the violated constraint key for country_id is displayed: One error saving changes to table “HR”.”LOCATIONS_TEMP”: Row 1: ORA-02291: integrity constraint (HR.LOC_TEMP_C_ID_FK) violated - parent key not found ORA-06512: at line 1

A foreign key constraint requires a value to exist in the referenced column of another table, i.e. enforcing the referential integrity. If you want to ensure that any records reference the deleted record will also be deleted, you can use ON DELETE CASCADE option. For example, if you want to ensure by deleting a country_id, all the records reference the deleted country_id are also removed, the SQL statement will be: country_id CHAR(2), CONSTRAINT loc_temp_c_id_fk FOREIGN KEY (country_id) REFERENCES countries (country_id) ON DELETE CASCADE

However, in practice, you probably would like to check the records first before deleting them. 100

UNSW SISTM Lab Manual

7.9.3 Composite Primary Key The composite primary key consists of two or more columns. Instead of associating the primary key with only one column, we create a primary key encloses with a number of columns. -- Create a composite primary key. CREATE TABLE global_region ( manager_id NUMBER(6,0), region_id NUMBER(2,0), job_id VARCHAR2(10), CONSTRAINT global_region_mgr_pk PRIMARY KEY (manager_id, region_id) );

When you create a single column primary key, a composite primary key, a foreign key, or any other constraints, you have to note the syntax of defining the constraint, and the position of the constraint in the CREATE statement. You also have to note the position of the comma (‘,’) used in the CREATE statement.

7.9.4 Using the UNIQUE Constraint The UNIQUE constraint is used to ensure that no duplicate values exist in the specified column(s). Unlike the PRIMARY KEY constraint, the UNIQUE constraint will allow NULL values to be entered into the column. -- Add a new column location_mnemonic and add a constraint for this column ALTER TABLE locations_temp ADD location_mnemonic CHAR(2) CONSTRAINT loc_temp_l_mn_uk UNIQUE; -- Alternatively, you can first add the new column location_mnemonic and then -- use another statement to add the constraint. ALTER TABLE locations_temp ADD location_mnemonic CHAR(2); ALTER TABLE locations_temp ADD CONSTRAINT loc_temp_l_mn_uk UNIQUE (location_mnemonic);

101

UNSW SISTM Lab Manual

7.9.4.1 Example: Unique Key Violation You cannot enter location_mnemonic ‘L5’ again but you can enter NULL value multiple times (Figure 7-7):

Figure 7-7 Unique Key Violation

7.10 Using the NOT NULL Constraint The NOT NULL constraint is to test a column that is NOT NULL, i.e. NULL value will not be accepted. This is in contrast to the UNIQUE constraint which allows NULL values. This constraint can only be created at the column level. ALTER TABLE table_name MODIFY ([column_name [CONSTRAINT constraint_name] NOT NULL); -- Modify the column first_name so it must have a value, i.e. NULL value cannot be accepted. ALTER TABLE employees_history MODIFY (first_name CONSTRAINT first_name_nn NOT NULL);

102

UNSW SISTM Lab Manual

7.11 CHECK Constraint The CHECK (condition) constraint is used to check the input value. You can use operators such as >, ALL’ operator, all the values of the parent query “must be greater than all the values in the subquery”, or the highest value returned by the subquery. In this case, the highest value returned by the subquery is $12,008 (see Figure 9-5).

Figure 9-5 Using the ALL Operator

123

UNSW SISTM Lab Manual

9.3.1.3 Example: Using the ANY Operator On the other hand, for the ‘> ANY’ operator, all the values of the parent query “must be greater than any of the values in the subquery”, or the lowest value returned by the subquery. In this case, the lowest value returned by the subquery is $8,300 (see Figure 9-5). The query in Figure 9-6 is same as Figure 9-5 except the ANY operator is used instead of the ALL operator but the results are quite different. A total of 30 rows were retrieved for employees with salary greater than $8,300.

Figure 9-6 Using the ANY Operator

124

UNSW SISTM Lab Manual

9.4 Multiple-Column Subqueries A multiple-column subquery returns more than one column to the parent query and can be listed in the parent query’s FROM, WHERE or HAVING clause. Figure 9-7 shows the average salary for each of the departments.

Figure 9-7 Department’s Average Salary

9.4.1 Multiple-Column Subquery in a FROM clause When a multiple-column subquery is used in the parent query’s FROM clause, it creates a temporary table, also known as inline view, that can be used by other clauses of the parent query. The subquery’s results are treated like any other table in the FROM clause. For example, Figure 9-8 shows the employees whose salary is above their department’s average salary, and EAVG in the SELECT statement is a temporary table: (SELECT em.department_id, AVG(em.salary) avg_salary FROM employees em GROUP BY em.department_id) EAVG 125

UNSW SISTM Lab Manual

Figure 9-8 Subquery using JOIN in the From clause

9.4.2 Multiple-Column Subquery in a WHERE clause Figure 9-9 shows how you can identify employees whose salary is exactly same as the department’s average salary.

Figure 9-9 Subquery in the WHERE clause

126

UNSW SISTM Lab Manual

9.5 Nested Subqueries The order of execution is always the same – the innermost subquery is executed first, then the next highest level subquery is executed, and so on, until the outermost query is reached. In the case of Figure 9-10, the order of execution will be A (innermost query), followed by B, and finally C (parent query).

Figure 9-10 Order of Execution in Nested Subqueries

9.6 Correlated Subqueries So far, the subqueries we executed are called uncorrelated subqueries. The sequences of uncorrelated subqueries process are as follows: (1)

Inner query is executed first

(2)

The result is then passed from the inner query to the parent query

(3)

Parent query is executed

On the other hand, the process sequence for correlated subqueries is different: (1)

Inner query is executed once for each row processed by the parent query

(2)

Inner query references the row contained in the parent query

9.6.1.1 Example: Correlated Subqueries We want to find all the locations currently used in the department as shown in Figure 9-11. In the WHERE clause of the subquery, we test the condition: departments.location_id = locations.location_id Please note that the departments table is from the subquery whereas locations table is from the parent query.

127

UNSW SISTM Lab Manual

Figure 9-11 Correlated Subqueries

We could have used department table in the parent query but we want to demonstrate the use of the EXISTS clause. If you want to find which location is not currently assigned to any of the departments, you can use NOT EXISTS instead, i.e. to look for records that do not exist in the departments table.

Figure 9-12 Correlated Subqueries using EXISTS clause

There are 23 locations in the locations table, we already know there are 7 locations currently actively used in the departments table (see Figure 9-11). Therefore, you should have 16 locations currently not assigned in the departments table and the result of Figure 9-12 confirms this. 128

UNSW SISTM Lab Manual

9.7 MERGE Statement A MERGE statement is commonly used in the data warehousing environment. The MERGE statement allows multiple DML actions (i.e. INSERT, UPDATE and DELETE commands) to be conditionally performed while comparing data of two tables. This is best illustrated with examples. 9.7.1.1 Example: MERGE In this example, we will create two temporary tables (see Figure 9-13), namely regions_temp_one and regions_temp_two, based on regions table for demonstration. The regions_temp_one table has five rows whereas egions_temp_two table only has four rows. Dummy values are assigned to the fields in the region_name column (see Figure 9-14). This will allow us to demonstrate how these values are updated and overwritten with the MERGE statement.

Figure 9-13 MERGE Statement - Create temporary tables

129

UNSW SISTM Lab Manual

Figure 9-14 MERGE Statement - List Records in the temporary tables

In regions_temp_two table, four rows are updated and one row is added as shown in Figure 9-15. The two temporary tables contain the same records.

Figure 9-15 MERGE Statement - List Changes in temporary tables 130

UNSW SISTM Lab Manual

Lab Week 10 Views 10.1 Objectives The last topic you will learn is to create and drop a view. We only cover simple and complex views. You can update date values using a view but we will not cover this topic in this course. 10.1.1 Reference Casteel Chapter 13 10.1.2 Database The database used in this lab is HR database.

10.2 Background of Views A view contains no data of its own. A view is a logical table based on a table or another view. The view is stored as a SELECT statement in the data dictionary. The tables on which a view is based are called base tables. The two main purposes of using a view are to: reduce the complexity of some queries and restrict users’ access to sensitive data. There are four types of views and they are summarised as (see Table 10-1): Table 10-1 Four Types of Views

You can update a table using a VIEW but, in this course, we will not cover using DML in a View. Nor we will cover inline and materialized views. We will only cover simple views, complex views and dropping a view.

131

UNSW SISTM Lab Manual

10.3 Simple View The syntax for VIEW command is: CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view_table [(alias)] AS subquery [WITH [CHECK OPTION] [READ ONLY OPTION]] The rules for the Simple view statement: 

Use the CREATE VIEW clause to create a view



Use OR REPLACE clause if the view already exists.



Use FORCE if the underlying table does not exist at the time of creation



Provide new column names if necessary



WITH CHECK OPTION constraint – if used, prevents data changes that will make the data subsequently inaccessible to the view



WITH READ ONLY OPTION– prevents DML operations



Only references one table – no group functions, GROUP BY clause, or expressions

Before you create a view, you have to make sure the SELECT statement runs and the data retrieved is exactly what you want. Once a view is created, you can access the data using the SELECT statement. 10.3.1.1 Example: Simple View

Figure 10-1 An Example of a Simple View

132

UNSW SISTM Lab Manual

10.4 Complex View A complex view is like a simple view except a complex view may contain data from multiple tables or data created with the GROUP BY clause, functions, or expressions. 10.4.1.1 Example: Complex View In the previous lab, we created a complex SELECT statement to identify employees whose salary is exactly the same as the department’s average salary as shown in Figure 9-9. As an example, you can create a VIEW, as shown in Figure 10-2, to allow your colleagues to run the same SELECT statement as yourself. Once a view is created, you can, for example, use a WHERE clause to retrieve the data you require (see Figure 10-3).

Figure 10-2 An Example of a Complex View

133

UNSW SISTM Lab Manual

Figure 10-3 Using WHERE Clause in a VIEW

10.5 Dropping a View The syntax to drop a View: DROP VIEW view_table

10.5.1.1 Example: Dropping a View

Figure 10-4 Dropping a View

134

UNSW SISTM Lab Manual

Appendix A Sample Database Structures A.1 Sample Databases In this course, we use two sample databases: (i) HR database (provided by Oracle) and (ii) JustLeeBooks database (provided by Casteel). The lab materials are based on the HR database, and the lab exercises are based on the JustLeeBooks database.

A.2 HR (Human Resources) Database The Oracle database sample schemas portray a sample company. The HR database tracks information about the employees and facilities. In the Human Resource (HR) records, each employee has an identification number, email address, job identification code, salary, and manager. Some employees earn commissions in addition to their salary. The company also tracks information about jobs within the organisation. Each job has an identification code, job title, and a minimum and maximum salary range. Some employees have been with the company for a long time and have held different positions within the company. When an employee resigns, the duration the employee was working for, the job identification number, and the department are recorded. The sample company is regionally diverse, so it tracks the locations of its warehouses and departments. Each employee is assigned to a department, and each department is identified either by a unique department number or a short name. Each department is associated with one location, and each location has a full address that includes the street name, postal code, city, state or province, and the country code. In places where the departments and warehouses are located, the company records details such as the country name, currency symbol, currency name, and the region where the country is located geographically.

135

UNSW SISTM Lab Manual

A.3 The HR Entity Relationship Diagram

Figure A-1 ER Diagram for HR Database

A.4 The Human Resources (HR) Table Descriptions A.4.1 countries Table

A.4.2 departments Table

136

UNSW SISTM Lab Manual

A.4.3 employees Table

A.4.4 job Table

A.4.5 job_history Table

137

UNSW SISTM Lab Manual

A.4.6 locations Table

A.4.7 regions Table

A.5 JustLeeBooks Database This is an Oracle sample schemas for Just Lee book store. This database tracks information about the customers, orders and promotions. The database structure of JustLeeBooks is shown below (Figure A-2 ), and you can find the table descriptions of JustLeeBooks database in Casteel, Appendix A (pp. 511-517).

Figure A-2 JustLeeBooks ER Diagram

138

UNSW SISTM Lab Manual

Appendix B Instructions to connect to a server database in Oracle SQL Developer 1. Select Oracle SQL Developer from the menu. 2. Your Oracle SQL Developer screen should look similar to Figure B-1:

Figure B-1 Select Configure File Type Associations

3. Select all Configure File Types associate with SQL Developer as shown in Figure B1, and click the OK button. 4. To connect to a database, you need to click the ‘+’ in Connections menu. A form, similar to Figure B-2, will prompt you to enter fields to connect to a server database:

Figure B-2 Server Database Connection Form 139

UNSW SISTM Lab Manual

5. The fields you have to enter in the form shown in Figure B-2 are as follows: Connection Name: Username: Password: Save Password:

Hostname: Port: SID:

HR z

(your student number) (your password – note the password is case sensitive) If you are running on your own laptop or other devices, you might want to click this box so you do not have to enter your password every time you log in. sage.business.unsw.edu.au 1521 orcl01 (note: the fourth character is ‘l’ for ‘Larry’ not ‘one’)

Once completed, your form should look similar to Figure B-3 (note: substitute the Username field with your student number):

Figure B-3 Database Connection Details

To test the connection, click the Test button as shown in Figure B-3. You will see an error if the connection is unsuccessful. Otherwise, click the Connect button to connect to the server database.

140

UNSW SISTM Lab Manual

6. Once connected, you will see two sets of tables as shown in Figure B-4: one set of tables is used in the Oracle Manual, and the other set is used in your lab exercises.

Figure B-4 Sample Tables

7. You need to format the dates to the DD-MON-RR. To change the date format, you need to go the option: Tools > Preferences > Database > NLS, and change the format to DD-MON-RR as shown:

Figure B-5 Set Date Format 141

UNSW SISTM Lab Manual

Appendix C Instructions to connect to Oracle SQL Developer Data Modeler Oracle SQL Developer Data Modeler is a data modeling and database design tool. For instance, you can use the tool to design an Entity Relationship Diagrams (ERD). You can download the software free from the Oracle website. You can create a database from scratch using Data Modeler. Alternatively, you can create an ERD by importing tables of a database you have already created. We will now demonstrate how to import tables from an existing database to Data Modeler. First, you have to select the Data Dictionary (or Ctrl-Shift-B) option from the File menu as shown in Figure C-1:

Figure C-1 Select Option to import a Data Dictionary

142

UNSW SISTM Lab Manual

You have to establish a connection to an existing database by following four steps as shown in Figure C-2:

Figure C-2 Connect to an existing database

Next, you have to choose a database and you might have to enter your username and password as shown in Figure C-3. In this case, we select the HR database:

Figure C-3 Select a Database 143

UNSW SISTM Lab Manual

Next, you have to select a schema/database – either student or group account - you want to use in your data modelling (Figure C-4):

Figure C-4 Select a Schema

Once you have connected to the schema, you then select the tables you want to model. As an example, the tables we selected as shown in Figure C-5 are countries, departments, employees, jobs, job_history and locations:

Figure C-5 Select Six Tables

144

UNSW SISTM Lab Manual

A summary of six tables imported is shown in Figure C-6:

Figure C-6 Summary of Number of Imported Tables

Once all the tables are imported successfully, a log similar to Figure C-7 appears, and clicks on the close button to complete the importing task:

Figure C-7 A Successful Log

145

UNSW SISTM Lab Manual

Data Modeler will automatically attempt to create an ERD based on the tables and constraints from the schema/database. The ERD shown in Figure C-8 is created based on the selected six tables:

Figure C-8 ERD for the Selected Tables

146

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF