Database Design and Implementation



Similar documents
IT2304: Database Systems 1 (DBS 1)

IT2305 Database Systems I (Compulsory)

SQL. Short introduction

3.GETTING STARTED WITH ORACLE8i

Introduction to Microsoft Jet SQL

Information Systems SQL. Nikolaj Popov

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

Higher National Unit specification: general information. Relational Database Management Systems

Programming with SQL


- Eliminating redundant data - Ensuring data dependencies makes sense. ie:- data is stored logically

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

Database Design. Marta Jakubowska-Sobczak IT/ADC based on slides prepared by Paula Figueiredo, IT/DB

DATABASE INTRODUCTION

P_Id LastName FirstName Address City 1 Kumari Mounitha VPura Bangalore 2 Kumar Pranav Yelhanka Bangalore 3 Gubbi Sharan Hebbal Tumkur

Database Query 1: SQL Basics

Database Administration with MySQL

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

Financial Data Access with SQL, Excel & VBA

Fundamentals of Database Design

Question 1. Relational Data Model [17 marks] Question 2. SQL and Relational Algebra [31 marks]

Once the schema has been designed, it can be implemented in the RDBMS.

MySQL for Beginners Ed 3

COMP 5138 Relational Database Management Systems. Week 5 : Basic SQL. Today s Agenda. Overview. Basic SQL Queries. Joins Queries

A Comparison of Database Query Languages: SQL, SPARQL, CQL, DMX

Chapter 6: Physical Database Design and Performance. Database Development Process. Physical Design Process. Physical Database Design

Using Multiple Operations. Implementing Table Operations Using Structured Query Language (SQL)

Files. Files. Files. Files. Files. File Organisation. What s it all about? What s in a file?

Chapter 9: Normalization

BCA. Database Management System

Physical Design. Meeting the needs of the users is the gold standard against which we measure our success in creating a database.

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

Oracle SQL. Course Summary. Duration. Objectives

Oracle Database 11g SQL

ORACLE 10g Lab Guide

Information and Computer Science Department ICS 324 Database Systems Lab#11 SQL-Basic Query

In This Lecture. SQL Data Definition SQL SQL. Notes. Non-Procedural Programming. Database Systems Lecture 5 Natasha Alechina

Oracle Database 10g: Introduction to SQL

Unit 2.1. Data Analysis 1 - V Data Analysis 1. Dr Gordon Russell, Napier University

SQL Server. 1. What is RDBMS?

B.1 Database Design and Definition

Oracle 10g PL/SQL Training

Oracle Database: SQL and PL/SQL Fundamentals

7. Databases and Database Management Systems

Instant SQL Programming

Structured Query Language. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics

Bridge from Entity Relationship modeling to creating SQL databases, tables, & relations

A basic create statement for a simple student table would look like the following.

The process of database development. Logical model: relational DBMS. Relation

Structured Query Language (SQL)

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Information Technology NVEQ Level 2 Class X IT207-NQ2012-Database Development (Basic) Student s Handbook

ICAB4136B Use structured query language to create database structures and manipulate data

GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD, GUJARAT. COURSE CURRICULUM COURSE TITLE: DATABASE MANAGEMENT (Code: ) Information Technology

Oracle Database 12c: Introduction to SQL Ed 1.1

Data Analysis 1. SET08104 Database Systems. Napier University

SQL SELECT Query: Intermediate

Microsoft Access 3: Understanding and Creating Queries

Oracle Database: SQL and PL/SQL Fundamentals NEW

Introduction to SQL for Data Scientists

Relational Data Analysis I

Normalisation 6 TABLE OF CONTENTS LEARNING OUTCOMES

How To Create A Table In Sql (Ahem)

Foundations of Information Management

Tutorial on Relational Database Design

Unit 3.1. Normalisation 1 - V Normalisation 1. Dr Gordon Russell, Napier University

Oracle Database: SQL and PL/SQL Fundamentals

Introduction to Computing. Lectured by: Dr. Pham Tran Vu

Normalisation to 3NF. Database Systems Lecture 11 Natasha Alechina

Oracle Database: Introduction to SQL

Using SQL Server Management Studio

- Suresh Khanal. Microsoft Excel Short Questions and Answers 1

Access Queries (Office 2003)

RDBMS Using Oracle. Lecture Week 7 Introduction to Oracle 9i SQL Last Lecture. kamran.munir@gmail.com. Joining Tables

Database Programming with PL/SQL: Learning Objectives

Database Design Methodology

Oracle Database: Introduction to SQL

Database Design. Adrienne Watt. Port Moody

Database Design Methodology

DBMS / Business Intelligence, SQL Server

Unit 10: Microsoft Access Queries

A Brief Introduction to MySQL

Participant Guide RP301: Ad Hoc Business Intelligence Reporting

Creating Tables ACCESS. Normalisation Techniques

MYSQL DATABASE ACCESS WITH PHP

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

C HAPTER 4 INTRODUCTION. Relational Databases FILE VS. DATABASES FILE VS. DATABASES

Talking to Databases: SQL for Designers

Normalization in Database Design

6 CHAPTER. Relational Database Management Systems and SQL Chapter Objectives In this chapter you will learn the following:

Select the Crow s Foot entity relationship diagram (ERD) option. Create the entities and define their components.

David M. Kroenke and David J. Auer Database Processing: Fundamentals, Design and Implementation

SQL Server 2008 Core Skills. Gary Young 2011

Why & How: Business Data Modelling. It should be a requirement of the job that business analysts document process AND data requirements

Relational Database Basics Review

Topics Advanced PL/SQL, Integration with PROIV SuperLayer and use within Glovia


A table is a collection of related data entries and it consists of columns and rows.

Transcription:

Database Design and Implementation A practical introduction using Oracle SQL Howard Gould 1

Introduction These slides accompany the book Database Design and Implementation A practical introduction using Oracle SQL By Howard Gould Available to download for free from:- bookboon.com/en/database-design-and-implementation-ebook Supporting materials available from: howard-gould.co.uk 2

1. Introduction to database development Databases are at the centre of most information systems Important to design and build using appropriate methods Ensure that they meet users requirements Need to be robust and maintainable 3

1. Introduction to database development A Database system consists of: Database - related tables of data Maintained by Database Management System (DBMS) Applications that provide controlled access to database (pages, forms, reports) 4

1. Introduction to database development Database development lifecycle: 1. Strategy and planning identify need and scope of system 2. Requirements analysis identify detailed requirements (conceptual) 3. Design conceptual, logical & physical design 4. Development using a DBMS e.g. Oracle APEX 5. Deployment/implementation testing and release 6. Operations and maintenance use of system until lifecycle starts again. 5

1. Introduction to database development Conceptual data modelling Why do you need to model? To ensure product will meet the users requirements Modelling allows stakeholders to check the design How do you model a database system? Entity Relationship Modelling (A top down analysis approach) Entity Relationship Diagram (ERD) or UML Class Diagram (CD) Shows business data structure - relationships between the data entities. 6

1. Introduction to database development Entity Relationship Diagram (ERD) Shows Entities Relationships link the entities Entity formally called an entity type Represents data items needed by the system Music System ERD 7

1. Introduction to database development Entity types: Physical - CAR, BUILDING Human - CUSTOMER, EMPLOYEE Place - FACTORY, SCHOOL Group - DEPARTMENT, TEAM Document - INVOICE, PAYSLIP 8

1. Introduction to database development Producing the ERD Use a Computer Aided Software Development (CASE) tool e.g. QSEE super;ite 1.1 from http://www.leedsbeckett.ac.uk/qsee/ 9

1. Introduction to database development Entity attributes Entities consist of data attributes e.g. for an occurrence of the entity INVOICE Attributes: Attribute values: Invoice number 1102 Invoice date 12-Jan-2015 Invoice amount 1000 Customer code C101 10

1. Introduction to database development Entity selection and validation Candidate entities should be checked: 1. Should not be name of the system being modelled 2. Should be of importance to the system being studied 3. Should have data attributes that can be associated with the entity All entities must have a unique identifier Identifying attribute(s) used to uniquely identify an occurrence of an entity. 11

1. Introduction to database development Entity type: Attributes: Identifier: Occurrence: STUDENT Student ID, Name, Address, Post Code, Date of Birth Student ID S101, Paul Adams, 4 Long Row Leeds, LS6 3QS, 12-Jan-1960 Entity: Attributes: Identifier: Occurrence: COURSE Course code, Course name, Start date Course code COMP, BSc. Computing, 01-Sep-2015 12

1. Introduction to database development Entity definitions needed to recorded Stored in data dictionary or data repository Entity type Entity definition Entity Attributes CUSTOMER A person or organisation who purchases products or services from the business. Customer name, Address, Postcode, Customer code, Phone number. INVOICE A request to a customer for payment for products or services supplied by the business. Invoice Date, Invoice number, Invoice Amount, Customer code. 13

1. Introduction to database development Validating the model Checked with client and/or system users Remember it is easier and cheaper to change a model than it is to change a developed system. 14

2. Entity Relationships Entities do not exist in isolation Need to identify relationships that link them together Form the Entity Relationship Diagram (ERD) Important to understand how one occurrence of an entity relates to an occurrence of another entity Need to view the relationship from both directions in order to define the relationship accurately. 15

2. Entity Relationships Relationship STUDENT studies COURSE Consider relationship from both directions Always use UPPER case text to label entities and lower case text to label relationships. 16

2. Entity Relationships Relationship cardinality How many occurrences of one entity related to another Three relationship types One to One abbreviated as 1:1 One to many abbreviated as 1:M Many to Many abbreviated as M:M or M:N 17

2. Entity Relationships One to many (1:M) The crow s foot symbol is used to represent many and is placed at the many end of the relationship. The relationship would be read formally as a student studies one and only one course and a course is studied by one or many students. 18

2. Entity Relationships Many to many (M:N) Crow s foot symbol at both ends of relationship This relationship would now be read as a student studies one or many courses and a course is studied by one or many students. 19

2. Entity Relationships One to one (1:1) The relationship would be read as a student is supervised by one and only one lecturer and a lecturer supervises one and only one student. 20

2. Entity Relationships Relationship optionality An occurrence of an entity may not always be present (i.e. optional or zero) Small circle is included on the relationship line at the end that is optional This diagram would be read as a student is supervised by one and only one lecturer and a lecturer supervises zero or one student. Notice that the optionality is placed at the opposite end of the relationship to the entity on which you are concentrating. 21

2. Entity Relationships A many to many relationship with optionality Read as A student studies one or many courses and a course is studied by zero, one or many students The little vertical bar on the relationship represents one occurence Think of the inner relationship symbol as the minimum and the outer symbol as the maximum number of occurrences. In the example above the inner symbols used are o and and the crow s feet are the outer symbols. 22

2. Entity Relationships The reading of the relationship starts with one whatever the cardinality at that end is. Always read the relationship in BOTH directions to ensure you have correctly identified the cardinality and optionality for both ends of the relationship. 23

2. Entity Relationships Label relationships clearly To avoid misinterpreting the relationship and cardinality e.g. Two different relationships possible with same entities but different cardinality and optionality LECTURER teaches STUDENT is taught by 24

3. Complex relationships Associative relationships Many to many relationships hold data Replaced with new link entity and two 1:M relationships 25

3. Complex relationships Link entity identifier Usually uses both original entity identifiers together to form its identifier E.g. for invoice ITEM use invoice no. and Product code together In some cases may need an additional attribute to ensure identifier is unique 26

3. Complex relationships Recursive relationships e.g. EMPLOYEE manages other EMPLOYEEs An EMPLOYEE manages zero, one or more other EMPLOYEEs, and an EMPLOYEE is managed by zero or one other EMPLOYEEs. Note the V-C isn t managed by anyone and not all employees manage other employees. 27

3. Complex relationships Sub types Some entity types have sub types which contain different attributes Main entity called a Super type The sub type identifier is the same as the super type identifier Sub types can show relationships more accurately i.e. relationship between an entity and a sub type 28

3. Complex relationships Exclusive relationships Can be used when two or more relationships are mutually exclusive Arc symbol used e.g. a VEHICLE may undergo a SERVICE or an INSPECTION but not both. 29

3. Summary Entity Attribute Identifying attribute Relationship Cardinality A data object of interest to the system A property of an entity An attribute or combination of attributes that uniquely identifies an entity occurrence. An association between two entities The number of occurrences in one entity that can have a relationship with the occurrences in another entity one to one 1:1 one to many 1:M or 1:m many to one M:1 or m:1 many to many M:N or m:n (or M:M) Optionality Participation in a relationship 30

4. Logical Database Design Convert the conceptual design ERD into a Logical Design Logical Design consists of a set of RELATIONS (not to be confused with relationships) similar to tables This design will become a set of tables suitable for implementation using a relational database management system e.g. MS Access, Oracle etc. Example of a relation for the entity type CUSTOMER: CUSTOMER (Customer_no., name, address, date_of_birth,... ) Customer_no. is the unique identifier now referred to as Primary Key(PK) 31

4. Logical Database Design Keys a key uniquely identifies an entity occurrence: it is the entity identifier a primary key is the key chosen for a given relation / table a candidate key is a possible primary key (several candidate keys may exist for a relation) a compound key is a key consisting of two or more attributes. VEHICLE (vehicle identification no., registration_no., vehicle_make, vehicle_model,..) vehicle identification no. and vehicle registration_no are candidate keys Attribute names don t include spaces (use underscores from now on). 32

4. Logical Database Design Identifying relations Relations need keys to reflect the relationships between entities These are called Foreign Keys (FK) An FK is an attribute in a relation which exists as a PK in another relation Primary keys shown in BOLD, underline or both. Foreign Keys shown in Italics 33

4. Logical Database Design This ERD would result in the following two relataions: CUSTOMER ( Customer no., customer name, customer_address,..) BOOOKING (Booking ref., Booking_date, Customer_no, ) For a 1:M relationship with no optionality at the one end, the primary key from the one end of the relationship is included at the many end as a foreign key. 34

4. Logical Database Design Resolving a M:N relationship Gives three skeletal relations (skeletal relations only show keys): STUDENT ( Student_id) MODULE ( Module_Id) STUDY ( Student_id, Module_id) New relation has a compound Primary Key consisting of the two Foreign Keys 35

4. Logical Database Design Resolving a 1:M relationship with optionality at the one end Gives three skeletal relations: CAR (Car_reg.) CUSTOMER (Customer_no.) HIRED_CAR (Customer_no., Car_reg.) With a 1:M with optionality a new relation is needed to avoid having a NULL foreign key 36

4. Logical Database Design Resolving a 1:1 relationship Gives ONE relation: EMPLOYEE (Employee_No, Computer_ID ) or COMPUTER (Computer_ID, Employee_No) Choice depends on purpose of the system remaining attributes would be same whichever is chosen 37

4. Logical Database Design Resolving a 1:1 relationship with optionality at one end Gives relations: EMPLOYEE ( Employee_No) COMPUTER ( Computer_ID, Employee No) This approach avoids ending up with NULL value FK Employee_No. 38

4. Logical Database Design Resolving a 1:1 relationship with optionality at both ends Gives relations: EMPLOYEE (Employee_No) COMPUTER ( Computer_ID) COMPUTER_ALLOCATION (Employee_No, Computer_ID) Either original identifier could have been used for the new relation 39

4. Logical Database Design Resolving recursive relationships EMPLOYEE (Employee_No, emp_name) becomes EMPLOYEE (Employee_No, emp_name, mgr_emp_no) EMPLOYEE (Employee_No, emp_name) and MANAGER (Employee_No, mgr_emp_no) EMPLOYEE (Employee_No, emp_name, ) and MANAGER (Employee_No, mgr_emp_no) 40

4. Logical Database Design Resolving exclusive relationships VEHICLE (Registration_no) SERVICE (Service_no, Registration_no) INSPECTION (Inspection_no, Registration_no) Foreign keys placed in the optional relations to avoid NULL values 41

4. Logical Database Design Identification dependency Where key from non dependent (one) end of relationship becomes part of the key at the dependent end of the relationship HALL (Hall_name) APARTMENT (Hall_name, Apartment_no) ROOM (Hall_name, Apartment_no, Room_no) An entity is referred to as strong if its primary key is not dependent on another entity. An entity is referred to as weak if its primary key is partially or wholly made up of attributes from other entities, as in a link entity created from a M:N relationship, or where an attribute from within an entity is used with a foreign key to form a compound primary key. 42

4. Logical Database Design Modelling problem Fan trap Solution Not possible to link from student to module Modelling problem Chasm trap Solution Optionality prevents linking course and student 43

5. Normalisation A process used to produce a logical design which will lead to an efficient and effective database (avoiding wasted storage space & data redundancy/duplication) Formal technique for analysing individual relations Transforms the relations to a form referred to as normalised Relations can be in one of four states: Un-normalised (UNF) 1 st Normal Form (1NF) 2 nd Normal Form (2NF) 3 rd Normal Form (3NF) 44

5. Normalisation Important to avoid data redundancy storing the same data in more than one place has the potential to produce anomalies that can arise when data is inserted, amended or deleted. E.g. If customer details stored in more than one place but not all are updated ERD s - logical design will be normalised to some extent If database is designed using a bottom-up approach from existing system documents initial logical design is unlikely to be normalised. 45

5. Normalisation The following shows the process for normalising relations i.e. converting from UNF to 3 rd NF Un-normalised form (UNF) An un-normalised table can be defined as having any of the following issues: there are repeating groups (of attribute names) the attribute values are not atomic (single) there are embedded tables Do not normalise all the attributes as one data set, normalise each logical data set separately. 46

5. Normalisation A worked example 47

5. Normalisation UNF Invoice_No Invoice_Date Customer_No Invoice_Name Invoice_Address (Item_ID Description Qty Price Amount) Subtotal Tax Delivery Total The attributes shown between the ( ) form a repeating group. 48

5. Normalisation To convert to 1NF 1. Identify the primary key for the relation (you may have to invent one) 2. Identify the repeating group or groups of attributes 3. Remove the repeating group completely from the original relation and place it in a newly- created relation. 4. Ensure the relations are linked by putting the primary key of the original relation into the new one as a foreign key. 5. Define a primary key for the new relation. This usually consists of two attributes, one of which is the Foreign Key, but there could be more than two. 49

5. Normalisation 1NF Un-normalised form Invoice_No Date Customer_No Invoice_Name Invoice_Address (Item_ID Description Qty Price Amount) Subtotal Tax Delivery Total First normal form Invoice_No Date Customer_No Invoice_Name Invoice_Address Subtotal Tax Delivery Total Invoice_No Item_ID Description Qty Price Amount 50

5. Normalisation 2NF A relation is in Second Normal Form if It is already in 1NF and All non-key attributes are fully functionally dependent on the whole key. Conversion from 1NF to 2NF Identify attributes with partial key dependencies Remove the attributes with partial key dependencies into a new relation Make the part key they are dependent on the primary key for the new relation Do not forget to ensure that the original relation retains its compound key. 51

5. Normalisation 2NF Un-normalised form First Normal Form Second Normal Form Invoice_No Invoice_No Invoice_No Date Date Date Customer_No Customer_No Customer_No Invoice_Name Invoice_Name Invoice _Name Invoice_Address Invoice_Address Invoice_Address (Item_ID Subtotal Subtotal Description Tax Tax Qty Delivery Delivery Price Total Total Amount) Subtotal Invoice_No Invoice_No Tax Item_ID Item_ID Delivery Description Qty Total Qty Amount Price Amount Item_ID Description Price 52

5. Normalisation 3NF A relation is in Third Normal Form if - it is already in 2NF there are no functional dependencies between any pair of non-key attributes (i.e. there are no transitive dependencies) Conversion from 2NF to 3NF Identify any attributes that are determined by another non-key attribute Remove these attributes to a new relation Set the non-key attribute to be the Primary key in the new relation Convert the non-key attribute to a foreign key in the original relation. 53

5. Normalisation Un-Normalised Form UNF First Normal Form 1NF Second Normal Form 2NF Third Normal Form 3NF Relation Name Invoice_No Invoice_No Invoice_No Invoice_No INVOICE Date Date Date Date Customer_No Customer_No Customer_No Customer_No 3NF Invoice_Name Invoice_Name Invoice_Name Invoice_Name Invoice_Address Invoice_Address Invoice_Address Subtotal (Item_ID Subtotal Subtotal Tax Qty Tax Tax Delivery Description Delivery Delivery Total Price Total Total Amount) Invoice_Name INVOICE ADDRESS Subtotal Invoice_No Invoice_No Invoice_Address Tax Item_ID Item_ID Delivery Qty Qty Invoice_No INVOICE ITEM Total Description Amount Item_ID Price Qty Amount Item_ID Amount Description Price Item_ID ITEM Description Price 54

5. Normalisation Compare top down approach (ERD) with bottom up (relations) Denormalisation may be used for performance reasons Add any new relations identified to original ERD to form a composite model 55

5. Normalisation To help you remember the 3 normal forms, the attributes in a relation should depend on: 1NF the key 2NF the whole key 3NF nothing but the key 56

6. Introduction to Oracle SQL Physical design can now be implemented using a Relational Database Management System (RDBMS) e.g. ORACLE, MySQL, Microsoft SQL Server and Microsoft Access DBMS uses Structured Query Language (SQL) to manipulate the data SQL commands The following examples use ORACLE database with Oracle Application Express (APEX) Note there are slight differences in SQL between different RDBMSs 57

6. Introduction to Oracle SQL Creating tables CREATE TABLE tablename (column_name datatype [constraint_name constraint type],..); [ ] represents and optional clause Table and column names must follow these rules: the table name must be unique it can be up to 30 characters long it must start with a letter it can have letters, digits and the symbols $, # and _ the name cannot be a reserved word (e.g. an Oracle SQL command) Note CREATE TABLE tablename will not replace an existing table with same name. You should use the DROP tablename command first. 58

6. Introduction to Oracle SQL Columns must have a datatype and usually a size defined e.g.: Fixed length character string CHAR Variable length character string VARCHAR2 Numbers NUMBER Date DATE Timestamp TIMESTAMP Example column sizes for CHAR, VARCHAR2 and NUMBER columns: CHAR(3) Holds strings of 3 characters (right filled with spaces ) VARCHAR2(25) Holds strings up to 25 characters long (variable length no padding) NUMBER(3) Holds integers up to three digits long e.g. -999 to 999 NUMBER(5,2) Holds real numbers e.g. - 999.99 to 999.99 The total number of digits (5) is referred to as the precision and the decimal places (2) are referred to as the scale. 59

6. Introduction to Oracle SQL Constraints Table & Row e.g. Primary Key, Foreign Key (can be compound made up from 2 or more attributes) Categories Integrity Primary key to ensure duplicate rows cannot be added to a table Foreign key ensures a row must reference a primary key in the referenced table Value NOT NULL ensures that a value must be entered (cannot be left empty) CHECK ensures that a column has a value within a set range e.g. CHECK ( price > 10) and (price < 20) UNIQUE ensures a single column has a unique value or that a group of columns is unique 60

6. Introduction to Oracle SQL Create table commands for the music system CREATE TABLE company( CREATE TABLE category( company_id number(3) PRIMARY KEY, cat_id number(3) primary key, company_name varchar2(20) NOT NULL, cat_description varchar2(20) NOT NULL); company_country varchar2 (15) NOT NULL, company_phone varchar2 (15) NOT NULL); CREATE TABLE cd( CREATE TABLE track( cd_idno number(3) PRIMARY KEY, track_cd number(3) references cd(cd_idno), cd_title varchar2(50) NOT NULL, track_no number(3) NOT NULL, cd_artist varchar2(30) NOT NULL, track_title varchar2(50) NOT NULL, cd_date_purchased date NOT NULL, track_length number(4,2), cd_payment_type varchar2(6), track_cat_id number(3) references category(cat_id), cd_price number(4,2), Primary key(track_cd,track_no)); cd_company_id number(3) references company(company_id)); 61

6. Introduction to Oracle SQL Inserting data inserting rows of data INSERT INTO table_name (column_name, ) VALUES (column_value,...); or INSERT INTO table_name VALUES (column_value,...); e.g. INSERT INTO category(cat_id, cat_description ) VALUES (10, 'Bhangra'); or INSERT INTO category VALUES (10, 'Bhangra'); 62

6. Introduction to Oracle SQL Ensure that the data values you are trying to enter match the type and fit the size of their defined data columns. Character strings and dates should be enclosed between a pair of single quotation marks not double marks. Note the single quotation marks will appear like this ' ' when viewed in Oracle APEX. To enter a null or empty string into a column, just use two single quotation marks together with no space in between them Remember duplicate primary key values in a table are not permitted. 63

6. Introduction to Oracle SQL Deleting data removing rows of data DELETE FROM tablename WHERE condition(s); e.g. DELETE FROM company WHERE company_id = 10; Warning: DELETE FROM tablename without a WHERE condition will delete all the rows. 64

6. Introduction to Oracle SQL Updating data updates row values UPDATE tablename SET condition WHERE condition e.g. UPDATE company SET company_name = 'BMB' WHERE company_id = 10; Note if you leave off the WHERE condition all rows in the table will be updated. 65

7. Using Foreign Keys Foreign Key used to reference a PK in another table Foreign key in CD table references COMPANY table e.g. cd_company_id number(3) references company(company_id)); Track table has two FK s to reference CD and CATEGORY tables track_cd number(3) references cd(cd_idno), and track_cat_id number(3) references category(cat_id), 66

7. Using Foreign Keys Can t DROP a table that has a Primary key that is referenced by another table Need to use CASCADE CONSTRAINTS e.g. DROP TABLE cd CASCADE CONSTRAINTS Note constraints can be added using ALTER TABLE command 67

8. Selecting data from a table Selecting data from a table SELECT [DISTINCT] column_name,. FROM table_name [,.] [WHERE condition(s)] [ORDER BY column_name [ASC DESC] ]; DISTINCT clause can be used to eliminate duplicate values being displayed WHERE condition allows you to specify selection criteria to restrict the data retrieved ORDER BY clause allows you to sort the output into Ascending (default) or Descending order before it is displayed. 68

8. Selecting data from a table Selecting all the data from a table To show all the columns for each row in the category table use the following: SELECT cat_id, cat_description FROM category; Alternatively, to view all the columns of data for a table without listing them by name, use the * symbol as follows: SELECT * FROM category; 69

8. Selecting data from a table Selecting some rows of data from a table Need to use WHERE clause with a condition which uses a comparison operator Comparison Operator Description = Equal to < Less than > Greater than <= Less than or equal to >= Greater than or equal to SELECT * FROM COMPANY WHERE company_country = 'UK' ORDER BY company_name; <> Not equal to!= Not equal to BETWEEN val1 AND val2 Value range IN(val1,val2, val3 ) In set of values 70

8. Selecting data from a table Compound conditions formed using logical operators AND, OR, NOT AND operator is used when all the simple conditions must be true. OR operator is used when any simple condition can be true. NOT operator is used when a simple condition should be reversed i.e. not true. Some examples of compound conditions: SELECT * FROM cd WHERE cd_payment_type = 'cash' AND cd_price > 10; SELECT cat_description FROM category WHERE cat_description = 'pop' OR 'rock'; SELECT company_name FROM company WHERE NOT (company_country = 'UK'); 71

8. Selecting data from a table Computed columns not stored within the table use arithmetic operators Arithmetic Operator Description + Addition - Subtraction * Multiplication / Division An example which calculates the 20% tax exclusive element of a CD price: SELECT cd_title, cd_price, (cd_price / 1.2) AS ExTax FROM cd; 72

9. Selecting data from multiple tables Tables need to be joined (Equijoin or inner join) using a simple condition E.g. To extract cd titles and music track titles: SELECT cd_title, track_title FROM cd,track WHERE cd_idno = track_cd; If the join is left out then incorrect data will be output (called a Cartesian product): SELECT cd_title, track_title FROM cd,track; 73

9. Selecting data from multiple tables Self join an alias is used to reference a table simultaneously from 2 different rows superv ises EMPLOYEE is superv ised by CREATE TABLE employee ( employee_no VARCHAR2(6) PRIMARY KEY, name VARCHAR2(20), supervisor VARCHAR2(6) REFERENCES employee(employee_no)); employee_no, name, supervisor 701 B Boss 702 U Ling 701 703 A Lee 701 SELECT s.name FROM employee e, employee s WHERE e.supervisor = s.employee_no AND e.employee_no = '702'; 74

9. Selecting data from multiple tables Outer joins used to extract data using two tables which don t have shared column values. SELECT table1name.columnname, [tablen2ame.columnname] FROM table1name, table2name WHERE table1name.columnname(+) = table2name.columnname; To see music categories which include those that have not been used in the track table: SELECT track_title, track_cat_id, cat_id, cat_description FROM track, category WHERE track.track_cat_id(+) = category.cat_id; 75

9. Selecting data from multiple tables Built-in functions can be used within SELECT command: E.g. TO_DATE converts character strings to valid date format UPPER converts character strings to upper case LOWER converts character strings to lower case INITCAP converts 1 st character of a string to uppercase Conversions are only temporary, data column values are not changed. 76

9. Selecting data from multiple tables Built-in function examples SELECT cd_title, cd_date_purchased FROM cd WHERE cd_date_purchased = TO_DATE('28-JAN-2002', 'DD-MON-YYYY'); SELECT * FROM cd WHERE cd_title = UPPER('Best of Bowie'); SELECT * FROM cd WHERE INITCAP(cd_title) = 'Best Of Bowie' ; 77

10. Subqueries and group functions There are two types of sub query Single Row Multiple Row - returns only one row of data - returns more than one row of data. Single-row subquery general format SELECT column_name,. FROM table_name WHERE column_name relational operator (SELECT column_name, FROM table_name WHERE condition); e.g. SELECT track_title, track_cat_id FROM track WHERE track_cat_id = (SELECT cat_id FROM category WHERE cat_description = 'Pop'); 78

10. Subqueries and group functions Multiple-row subquery returns more than one row Can use the following operators Operator IN Matches any value in a list Use ALL Compares the given value with every returned subquery value E.g. SELECT Prod_desc FROM product WHERE product.prod_no IN (SELECT item.prod_no FROM item WHERE Order_no = 'Z01'); ANY or SOME Compares the given value with each returned subquery value 79

10. Subqueries and group functions Group functions operate on a group of rows but return a single value SUM(column_name) AVG(column_name) Function Description Calculates the total value of a column, null values are ignored. Finds the average of all the values in a column, null values are ignored. MAX(column_name expression) Finds the maximum value in a column or expression, null values are ignored. MIN(column_name expression) Finds the minimum value in a column or COUNT(* column_name expression) expression, null values are ignored. * Counts the number of rows, including nulls If a column or expression is used counts non null e.g. SELECT AVG(cd_price), MAX(cd_price), MIN(cd_price), SUM(cd_price) FROM cd; values. 80

10. Subqueries and group functions GROUP BY used with separate groups of rows SELECT column_name, group function (column_name) FROM table_name [WHERE condition(s)] [GROUP BY column_name expression] [ORDER BY column_name expression [ASC DESC]]; 81

10. Subqueries and group functions Examples SELECT track_cat_id, COUNT(*) no of tracks FROM track GROUP BY track_cat_id; In order to restrict groups, the HAVING clause can be used, so suppose you only wanted to see the number of tracks for music categories that had more than 16 tracks, the following could be used: SELECT track_cat_id, COUNT(*) no of tracks FROM track GROUP BY track_cat_id HAVING COUNT(*) > 16; 82

11. Creating pages & reports Databases use applications consisting of Pages(Forms) and Reports to access the data. Oracle APEX (Application Express) used to produce the web pages 83

11. Creating pages & reports APEX main tools Application Builder used to build pages & reports Various types of pages and reports can be produced 84

12.1 UML Modelling Notation A Class symbol representing an entity A Class symbol representing an entity with an attribute A class association (Binary relationship) 85

12.1 UML Modelling Notation Class association is used to represent relationship between two entity classes Multiplicity is shown to represent the cardinality and optionality 0..1 is read as zero or 1 1..1 is read as one and only 1 0..* is read as zero 1 or many 1..* is read as one or many 86

12.1 UML Modelling Notation Many to many relationship Association class 87

12.1 UML Modelling Notation Generalisation and specialisation VEHICLE class is the generalisation (super class) CAR and TRUCK are specialisations (sub types) 88

12.1 UML Modelling Notation ERD CLASS Diagram 89