0% found this document useful (0 votes)
70 views81 pages

Topic 8 Erd Views Visio-1

The document discusses multi-valued attributes in entity relationship diagrams and characteristic entities. It provides an example of an employee who has multiple skills as a multi-valued attribute. It then expands this into a separate junction table and discusses how characteristic entities can enforce referential integrity. Finally, it presents a case study on an online pizza ordering system and discusses modeling the order details and quantities as a many-to-many relationship.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views81 pages

Topic 8 Erd Views Visio-1

The document discusses multi-valued attributes in entity relationship diagrams and characteristic entities. It provides an example of an employee who has multiple skills as a multi-valued attribute. It then expands this into a separate junction table and discusses how characteristic entities can enforce referential integrity. Finally, it presents a case study on an online pizza ordering system and discusses modeling the order details and quantities as a many-to-many relationship.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Topic 8

Multi-Valued Attributes
Characteristic Entities
ERD Case Studies
Views
Visio

1
Multi-Valued Attributes
An ERDs may contain a multi-valued attribute (MVA) EmpNo
 An MVA is an attribute surrounded by {braces}. EmpName
{ Skill }
A multi-valued attribute is used when an attribute may
have more than one value for an entity instance.
 Eg. An Employee might have multiple skills etc.
EMPLOYEE

Example: Skill is a multi-valued attribute of EMPLOYEE


 Employee 15, Joe may have the following Skills:

'Forklift Driver'
'Crane Operator'
'Welder'

2
Multi-Valued Attributes
A multi-valued attribute, is a shortcut way of representing the fact that an Employee may
have many Skills.
• Below is an example of the same ERD after expanding the MVAs.
EmpNo SkillName
EmpName

EMPLOYEE Has a SKILL

 And we know that a M:M relationship must be converted if converting to a relational schema

EmpNo SkillName
EmpName

EMPLOYEE Has a EMPSKILL of a SKILL

3
Characteristic Entity

In this example the Skill entity is called a Characteristic Entity.

Characteristic Entity:
A Strong Entity with
EmpNo SkillName only key (identifier)
EmpName attributes

EMPLOYEE Has a EMPSKILL of a SKILL

4
Characteristic Entity
Some texts suggest that characteristic entities should be eliminated from an ERD.

After all, why bother with a separate table named Skill, when the data in the intersection
entity already contains ALL the data stored in a single row of Skill data? The Skill table does
not add any new data to the database.

EmpNo SkillName
EmpName

EMPLOYEE Has a EMPSKILL of a SKILL

EmpNo SkillName SkillName


15 Welder Electrician
17 Electrician Welder
17 Welder
5
Characteristic Entity
When building a database, a table based on a characteristic entity is useful.

The values in the Skill table are used as a foreign key constraint.
The foreign key constraint will force every SkillName value in the EmpSkill
table to match a Primary Key value in the referenced Table.

EMPLOYEE (EmpNo, EmpName)


PK (EmpNo)

SKILL (SkillName)
PK (SkillName)

EMPSKILL (EmpNo, SkillName)


PK (EmpNo, SkillName)
FK (EmpNo) References EMPLOYEE
FK (SkillName) References SKILL

6
Characteristic Entity
• Example: Using the Characteristic entity to force referential integrity
EmpNo EmpName EmpNo SkillName SkillName
15 Jim 15 Welder Electrician
17 Frank 17 Electrician Welder
19 Peter 17 Welder

EMPSKILL (EmpNo, SkillName)


PK (EmpNo, SkillName)
FK (EmpNo) References EMPLOYEE
FK (SkillName) References SKILL

Insert Into EmpSkill (EmpNo, SkillName) Values (15, "Electrician");


This statement is OK. The data is inserted.

Insert Into EmpSkill (EmpNo, SkillName) Values (15, "Plumber");


This statement fails. Referential Integrity Error or Foreign Key
7 constraint error. "Plumber" is not a PK of Skill.
Words and meanings
What is a class?
– Is that the same as a tutorial?
– Is it the same as a lab?

– Many staff / students use these terms interchangeably


(no disadvantage in using the wrong term).

However, within the Swinburne HR they have very different meanings


In the Payroll system, staff involved in these activities get paid at different rates!
If you are unsure on the meaning of a word or phrase – then ask
There is no such thing as a dumb question

War Story 1
– Pallets
– Streets / Aisles
– Bays / Slots / Locations

War Story 2
– Trucks & Split Trucks

8
Pizza Online
Case Study 1

9
Case Study - Overview

Let's consider a different business called Pizza OnLine

– It allows customers to order Pizzas via the WWW.


– Customers have pizzas delivered.
– Only people who register with a credit card number can be a an on-line
customer.

10
Case Study - Customer Details

• Customers need to supply personal details:

– Name
– Address
– Credit Card No

11
Case Study – Order Details

• The Order Form.


– This is One Order.
– The customer may add multiple items & different quantities

12
Case Study - Customer Details

• Add any delivery instructions that are required for the order:

13
Case Study – The completed Order
This Order is for
Customer C2045.

• Order Date & Time is


Sept 1, 2020 17:35

• This order has special


delivery instructions

• The order is for many


different Items.

• Each item ordered


has a Quantity value
14
Case Study – ERD

One order must have One customer.


One customer may make Many orders.

CustId ItemCode
Name DateTime Descripton
Address DeliveryInstructions ItemPrice

CUSTOMER makes ORDER for ITEM

• One order may refer to Many items


• One item may be referenced by Many orders

15
Case Study – Order Key

• What is the primary key of Order?


– CustID and DateTime
• Each business/organisation is different
– Some businesses would use OrderNumber instead
Warning:
– If OrderNumber is mentioned in the narrative then OK
– If OrderNumber is not mentioned in the narrative then NO

16
Where to place the Quantity attribute
• We need to place the Quantity attribute on the ERD
– It doesn't belong to Item
• It would mean an item always has the same quantity. Silly
– It doesn't belong to Order
• It would mean a cust orders the same quantity of each item. Silly

• Quantity must be attached to the M:M relationship

CustId ItemCode
Name DateTime Descripton
Address ItemPrice
DeliveryInstructions

CUSTOMER makes for ITEM


ORDER

Quantity
17
Pizza Online M:M
Again we have a M:M relationship
The M:M must be expanded

We create a diagram with an entity


called OrderLine.

One order has MANY orderliness.

Each orderline belongs to one order.


Each orderline refers to one item.

ItemCode
CustId
DateTime Descripton
Name
Delivery Quantity ItemPrice
Address Instructions

ORDERLINE ITEM
CUSTOMER ORDER for
has
makes

18
Pizza Online relational schema
– ORDER( CustId, DateTime, DeliveryInstructions)
PK: (CustId, DateTime)
FK: (CustId) references CUSTOMER

– ORDERLINE( CustId, DateTime, ItemCode, Quantity)


PK: (CustId, DateTime, ItemCode)
FK1: (CustId, DateTime) references ORDER
FK2: (ItemCode) references ITEM ItemCode
CustId
DateTime Descripton
Name
Delivery Quantity ItemPrice
Address Instructions

ORDERLINE ITEM
CUSTOMER ORDER for
has
makes

This diagram pattern is seen many times in business.


• A patron makes a loan from a library. The loan has many loan-lines.
• A store sends an invoice to a customer. The invoice has many invoice lines.
19
Pizza Online data

– Example of data for Order and OrderLine


ORDER
CustId DateTime Delivery Instructions
C2045 1 Sept 2020, 17:35 Use laneway entrance
ORDERLINE
CustId DateTime ItemNo Quantity
C2045 1 Sept 2020, 17:35 P1 2
C2045 1 Sept 2020, 17:35 P3 1
C2045 1 Sept 2020, 17:35 P4 1
C2045 1 Sept 2020, 17:35 B1 4
C2045 1 Sept 2020, 17:35 D1 2

20
Review: Weak Entity is central to solution

• What is the purpose of the pizza online system?

– To allow customers to order many items at a time

– To keep a history of orders that show who has ordered what

– The key entity in this ERD is the OrderLine weak entity

ItemCode
CustId
DateTime Descripton
Name
Delivery Quantity ItemPrice
Address Instructions

ORDERLINE ITEM
CUSTOMER ORDER for
has
makes

21
Review: Can't Order & Orderline be merged?
• Many students ask if Order and OrderLine should be merged.
• Answer: No.
• If merged every orderline would contain the delivery instructions
– Causing redundancy and potential update anomaly
• If the delivery instructions changed, then every row of the order would need to be updated.
CustId DateTime ItemCode
Name Delivery Instructions Descripton
Address Quantity ItemPrice

CUSTOMER ORDERLINE ITEM


has for

CustId DateTime ItemNo DeliveryInstructions Quantity


C2045 1 Sept 2020, 17:35 P1 Use laneway entrance and … 2
C2045 1 Sept 2020, 17:35 P3 Use laneway entrance and … 1
C2045 1 Sept 2020, 17:35 P4 Use laneway entrance and … 1
C2045 1 Sept 2020, 17:35 B1 Use laneway entrance and … 4
C2045 1 Sept 2020, 17:35 D1 Use laneway entrance and … 2
22
Can we use OrderNumber as a Primary Key?

• Within the ERD Model and Relational Model the Order is identified by
the CustID and DateTime. These are real world attributes.

– Do not include an attribute called OrderNo.


OrderNo has no real world meaning.

• When you actually come to build the database, then you may choose to
introduce a surrogate key such as OrderNo.

Obviously, if the business already uses order numbers, then OrderNo is a real world
attribute and can be used within the ERD and Relational model.

23
Glenferrie Toy Library
Case Study 2

24
Glenferrie Toy Library System
Let's re-examine the Glenferrie Toy Library.
• Previously each loan was for one item only

That requirement has changed.


• One loan may refer to many different items
• Need to record which library person conducted the loan process

Glenferrie Toy Library
Patron ID Card

Patron No: 12345678

25
Toy Library ERD modified
What changes are required ?

– The relationship for Loan and Toy becomes a M:M relationship

– The library staff member name is stored in the Loan entity

PatronNo
ToyNo
FirstName DateTimeBorrowed
ToyName
Surname
StaffName YearAquired
Gender

PATRON makes LOAN of TOY

26
Toy Library ERD modified

• The M:M relationship is expanded to reveal a weak entity

– The name of the weak entity is usually named something like

• LineItem (similar to OrderLine from the Pizza caser study)

PatronNo ToyNo
FirstName DateTimeBorrowed
ToyName
Surname
StaffName YearAquired
Gender

PATRON makes LOAN has LINEITEM for TOY

27
DateTime Returned
• Suppose that we want to include a DateTime Returned value
– For each toy as it is returned
– Toys may be returned on different days

– In which entity does DateTime Returned belong?

PatronNo ToyNo
FirstName DateTimeBorrowed
ToyName
Surname
StaffName YearAquired
Gender

PATRON makes LOAN has LINEITEM for TOY

28
DateTime Returned

• If DateTimeReturned is added to Loan, it means that

– All items for that loan must all be returned on the same date

• X Items may be returned on different days

• X Some items may not be returned at all

PatronNo
ToyNo
FirstName DateTimeBorrowed
StaffName ToyName
Surname
Gender DateTimeReturned YearAquired

PATRON makes LOAN has LINEITEM for TOY

29
DateTime Returned

• If DateTimeReturned is added to LineItem, it means that

– Each item may be returned on a different date

PatronNo
ToyNo
FirstName DateTimeBorrowed
StaffName ToyName
Surname
Gender DateTimeReturned YearAquired

PATRON makes LOAN has LINEITEM for TOY

30
Student Enrolment
Case Study 3

31
Student enrolment problem
• Reconsider the student enrolment problem from prior weeks…

STUDENT has ENROLMENT of SUBJECT

Grade
Address Description
Name Title
StuID SubCode

• In a University, this solution has limitations


– We have no idea when the student enrolled in a unit
– We cannot keep details of students who repeat a unit

• A University must record the year and semester of each student's


attempt at a subject
– E.g. Fred Smith may ⚫ fail INF10002 in Sem 1, 2020
⚫ pass INF10002 in Sem 2, 2020
32
Analysis of student enrolment problem
You could try adding Year and Semester SUBJECT
attributes to the Subject entity.
Year Title
Semester
Description
But this solution has limitations… SubCode

• Each instance of Subject contains redundant information


- E.g. The title and description values are identical and repeated…
SubCode Year Sem Title Description
INF10002 2020 1 Database Students who complete this unit of study should be
Analysis and able to: Describe the steps involved in database
Design design and database systems development.
INF10002 2020 2 Database Students who complete this unit of study should be
Analysis and able to: Describe the steps involved in database
Design design and database systems development.
INF10002 2021 1 Database Students who complete this unit of study should be
Analysis and able to: Describe the steps involved in database
Design design and database systems development.
33
Split Subject into Static data / Variable data

• A Subject is a combination of constant (static) data and variable data.

• Constant / Static attributes within a subject:


– Details do not change from semester to semester
» Subject Code
» Subject Title
» Subject Description
» Objectives …

• Variable attributes about a subject:


– Details do change from semester to semester
» Convenor
» Exam Date
» Text Book …
34
Analysis of student enrolment problem

• A solution to our enrolment scenario is to


split the existing subject entity into two entities

– The Subject entity stores static information


• There would only be one instance of subject INF10002

– The Subject Offering entity stores variable information pertaining to one


specific year/semester.
SUBJECT
of a SUBJECT
OFFERING

ExamDate
ConvenorID Description
Semester Title
Year SubCode
35
Analysis of student enrolment problem
– Subject INF10002 has one instance.
• There is only one subject INF10002

– Many Subject Offerings may exist for One Subject


– e.g. INF10002 may have many instances of Subject Offering
• INF10002, 2020, Sem1, Daphne Fowler, …
• INF10002, 2020, Sem2, Daphne Fowler, …
• INF10002, 2021, Sem1, Clare Moore, …

SUBJECT
of a SUBJECT
OFFERING

ExamDate
ConvenorID Description
Semester Title
Year SubCode
36
Analysis of Enrolment problem
SUBJECT
• Sample Data OFFERING
of a SUBJECT

ExamDate
ConvenorID Description
Semester Title
Year SubCode

Subject
SubCode Title Description
INF10002 Database Students who complete this unit of study should be able to:
Analysis and Describe the steps involved in database design and database
Design systems development.

Subject Offering
SubCode Year Semester ConvenorID Exam Date
INF10002 2020 1 Daphne Fowler 12 June 2020

INF10002 2020 2 Daphne Fowler 09 Nov 2020

INF10002 2021 1 Clare Moore 18 June 2021


37
Analysis of Enrolment problem

• Consider all students in INF10002


• With which entity should the student entity have a relationship with?

SUBJECT OR SUBJECT OFFERING

38
Analysis of Enrolment problem

• To enrol successfully a student must specify


– subject code
– year
– semester
⚫ A student must have a relationship with the subject offering entity

enrols SUBJECT OFFERING of a SUBJECT


STUDENT

ExamDate
StuId Convenor Description
StuName
Semester Title
Year SubCode

39
Analysis of Enrolment problem

• The M:M relationship is expanded revealing an 'Enrolment' entity


• The sample data shows a student who has enrolled in SubCode
Title SUBJECT
two separate offerings of INF10002. Description

of
has SUBJECT
STUDENT ENROLMENT of
OFFERING

ExamDate
Enrolment Data: StuID StuName Grade
Convenor
Semester
1234567, INF10002 , 2019, Sem2, N Year

1234567, INF10002 , 2020, Sem1, D


2233449, INF10002 , 2019, Sem1, HD
8888999, INF10002 , 2020, Sem1, P
1234567, INF10003 , 2019, Sem2 , P
1234567, INF30004 , 2020, Sem1, C
40
Offerings scenario

• The previous discussion about subject offerings applies to many scenarios:


– A series of performances by your favourite band while on tour.

TOUR OFFERING of a TOUR

Venue AtristName
TourName
Performance DateTime TourID

– Performances of a theatrical play


PERFORMANCE of a PLAY

TheatreName WrittenBy
Performance DateTime PlayName
PlayID

41
Is an 'offering' always required?

• When deciding if an 'offering' entity is required, ask yourself


– Is one instance of this entity offered multiple times
MEETING

DateTime
Agenda
Location
MeetingID

– The above ERD does not require a Meeting Offering entity


• Does one meeting have multiple offerings?
• No – one meeting can only have a single DateTime value

• In this case, a single Meeting entity is all that is required.

42
Business Narrative
• Consider this narrative:
– Hawthorn University has a number of subjects.
– Each subject is identified by a subject code and has a title
– Each subject may be run each semester of each year
– Each semester the subject may have a new convener
– A student is identified by student no.

– Student names, address and phone numbers are recorded.


– Students enroll for a subject in a particular year / semester.
– The grade for each enrolment is recorded.

– Each semester, each subject may have a number of assignments.


– Each assignments is identified by a number Ass1, Ass2, Ass3 etc.
– Each assignment has a narrative and a due date.

– Each student is awarded a score for their attempt at the assignment

43
ERD Rules
• There are no FIRM rules to building a good ERD

– Some students will start very slowly with few entities


– Some students will start with an ERD that may be almost complete within a few minutes
– It depends on:
• Experience with business problems
– More experience → generally faster ERD
• How many ERDs you have previously drawn
– More ERDs → generally faster ERD
• How many IT subjects you have completed in your degree
– More IT subjects → generally faster ERD

– You will make mistakes in your first few iterations.

– Mistakes often lead to a better understanding of the problem.


44
ERD Errors
• Will you draw a perfect ERD on the first attempt?
– Probably not. Unlikely. No
• Most ERDs are altered or redrawn during the process

• Are mistakes bad? Is redrawing an ERD a disaster?


– No
• Mistakes often lead to a better understanding of the problem
• As you find mistakes, make changes to ERD

• Should you spend time ruling boxes & lines for your first draft of an ERD?
– No (See above)

• Pencil is better than pen.


– Avoid software packages to draw first draft (See above)

45
Building the ERD
• Where do you start?
– Follow numbered steps from the last few lectures OR
– Start drawing by what 'feels' right
– Use 'patterns' that you have encountered before.
• Think of assignments / lab questions / sample exam questions

– Draw fewer entities rather then more entities.


• Modellers are always reluctant to remove an entity
once it has been drawn An Actor appears in Many Movies. A Movie has Many Actors
vs
– Draw M:M relationships to begin Actor may have many Castings. A Casting is for one Actor
A Movie may have many Castings. A Casting is for one Movie
• Fewer entities (see previous point)
• Gives better overall 'big picture' view of problem
• M:M relationships are generally easier to read in English

46
Dealing with obvious weak entities

– Should you draw only the STUDENT and SUBJECT entities with a M:M
relationship?
Year

Semester
STUDENT Enrols in SUBJECT
ConvenorName

Grade
Description
StuName Title
StuId SubCode

OR should you ….
47
Dealing with obvious weak entities

Or do should you draw SUBJECT OFFERING at the outset?

SUBJECT
STUDENT Enrols in of SUBJECT
OFFERING
Grade
ExamDate
Address Convenor Description
Name Semester Title
StuID Year SubCode

Either approach is OK. Do whichever is more comfortable.


ASSIGNMENT
If you know instantly that if a subject will have subjects offerings,
then why not start there. Description
AssId
48
Sequence of expansions

• This case study describes assignments


• When should the assignment entity and relationships be added to ERD?
– Before expanding the M:M relationship?
– After expanding the M:M relationship? SubCode
Title
Year
Description
Semester
STUDENT Enroils in SUBJECT
ConvenorName

Grade
StuName
StuId
ASSIGNMENT

DueDate
Description
AssId
49
Sequence of expansions
• This ERD shows the assignment having a relationship with Subject Before
expanding the M:M relationship
SubCode
Title
Year
Description
Semester
STUDENT Enroils in SUBJECT
ConvenorName

Grade
has
StuName
StuId
ASSIGNMENT

Due Date
Description
AssId
50
Sequence of expansions

• This ERD shows the assignment having a relationship with Subject Offering after
expanding the M:M relationship
Year
SubCode
Semester
Title
Convenor
ExamDate Description

SUBJECT
STUDENT Enrols in of SUBJECT
OFFERING
Grade
Address

Has
Name
StuID

Assignment is related to Subject ASSIGNMENT


Offering. This makes more sense.
Due Date
Assignments are created for each Description
AssId
Subject Offering. This semester's
assignments may be different to
last semester's assignments
51
Sequence of expansions

• When should you add a relationship between Student & Assignment?


– Before expanding Student / Subject Offering?
– After expanding Student / Subject Offering?
Year
SubCode
Semester
Title
Convenor
ExamDate Description

SUBJECT
STUDENT Enrols in of SUBJECT
OFFERING
Grade
Address

Has
Name
StuID

ASSIGNMENT

Due Date
Description
AssId
52
Sequence of expansions
• This ERD shows the assignment having a relationship with Student before expanding the M:M
relationship. This seems OK
• It seems to make sense to place it between Student & Assignment.
• A student may do many assignments.
• An assignment is attempted by many students
Year
SubCode
Semester
Title
Convenor
ExamDate Description

SUBJECT
STUDENT Enrols in of SUBJECT
OFFERING
Grade
Address

Has
Name
StuID

ASSIGNMENT
Attempts
Due Date

but wait...
Description
AssId
53
Sequence of expansions
• This ERD shows the assignment having a relationship with Enrolment after
expanding the M:M relationship. This is better.
• It makes more sense to only allow an enrolled Student to attempt assignments.
This matches business rules.
StuID

STUDENT Name

Address

Year
has SubCode
Semester
Title
Grade Convenor
ExamDate Description

ENROLMENT SUBJECT
In of SUBJECT
OFFERING

Has
AssId
ASSIGNMENT Description
Attempts Due Date
54
Sequence of expansions

• The ERD from a few slides previous allowed ANY student to attempt an INF10002
assignment.
• Students not enrolled in INF10002 this semester
must not be allowed to submit a INF10002 assignment
Year
SubCode
Semester
Title
Convenor
ExamDate Description

SUBJECT
STUDENT Enrols in of SUBJECT
OFFERING
Grade
Address

Has
Name
StuID

ASSIGNMENT
Attempts
Due Date
Description
AssId
55
Which way is the right way?

• While drawing the ERD for the enrolment problem there were many decision
points.
– Should I expand now or later?
– Should I draw a relationship now or later?

• There is no correct answer.


• Start drawing an ERD and learn.
• While drawing an ERD you will often learn / uncover problems, missing
relationships, incorrect relationships…
• It may take you two, three, four… attempts at an ERD to get it correct.

56
Test your model
• Could you write these SQL queries?
• Once you ERD is complete
• Which student had the best Ass1 score in
– Does it match Business Rules? INF30004 this semester?
– Can it be Navigated? • Who was convenor when student 1234567
was enrolled in INF10002?
– Does Test Data work?
StuID

STUDENT Name

Address

Year
has SubCode
Semester
Title
Grade Convenor
ExamDate Description

ENROLMENT SUBJECT
In of SUBJECT
OFFERING

Has
makes
Score
AssId
ASSIGNMENT Description
of ASSIGNMENT
ATTEMPT Due Date
57
Views
Storing Complex SQL Statements

58
Views
When discussing SQL views, think back to MS Access
– creating and storing queries in MS Access.
– You simply double clicked on a saved query name and
it retrieved data from tables.

A view is way to store a complex SQL Select command


and give it a name

Imagine this complex SQL statement:


SELECT e.empno, e.empname, e.deptid, b.bname
FROM EMPLOYEE e
INNER JOIN BRANCH b
ON e.bno = b.bno;
Suppose you could give the SQL statement a name: EmpView
Now, use that name in another SQL statement
SELECT *
FROM EMPVIEW ;
59
Views
• A view is the storage of an SQL statement.
• A view does not store data

• A view requires very little disk space


even though using the view may select millions of rows

• A view is often referred to as a virtual table.


– It looks like a table
– It behaves like a table
– It is not a table. It is simply a block of SQL code.

• The rows in the result set generated by the view are not saved.

• Each time the view is referenced, the SQL code in the view is executed.
60
Views
A view behaves just like a table
– Select columns from a view
– Use Where clause
– Use Join to link other tables and/or views

The view can now be treated like any table name


SELECT *
FROM EMPVIEW ; simple select

SELECT empname, bname


FROM EMPVIEW some columns
WHERE empno = 15; some rows

SELECT e.empname, d.deptname


FROM EMPVIEW e
INNER JOIN DEPARTMENT d joined with
ON e.deptid = d.deptid; other tables
61
View of an Aggregation Query
Another example of a view based on a complex Aggregation Query
CREATE VIEW EMPAVG AS
SELECT d.deptname, Avg(e.Salary) "Average Salary"
FROM EMPLOYEE e,
INNER JOIN DEPARTMENT d
ON e.deptid = d.deptid;
GROUP BY d.deptname
HAVING Avg(e.Salary) >= 50000

The above code is hard to learn & time consuming to type.


Select a view name when
Using a view in SQL is easier to type importing data into power BI
SELECT *
FROM EMPAVG

62
Views & security
• Imagine we have table Employee. It has a mixture of private & public data

– Some data should be queried by anyone


• (staffno, staffname, office_no, phone_no…)

– Some data should be queried only by management staff


• (salary, annual_leave_days, home_phone_no…)

– Some data should only be updated by Payroll staff


• (salary, annual_leave_days)

StaffNam PhoneN HomePhon


StaffNo e OfficeNo o Salary AnnualLeave e
ANYONE ANYONE ANYONE ANYONE
MGMT MGMT MGMT
PAYROLL PAYROL

63
Views & security
• Create Multiple views
– Emp_Anyone_View (green columns from previous slide)
– Emp_Mgr_View (Employee_Anyone_View + blue columns …)
– Emp_Payroll_View (Emp_Mgr_View + red columns)

• Database Administrators can create groups.


• Every staff member is a member of one or more groups

– Deny Read / Write access of Employee table to anyone

– Grant Read access to Employee_AllUser_View for AllUsers


– Grant Read access to Employee_Mgr_View to Mgr group
– Grant Read / Write access to Emp_Payroll_View to Payroll group

– Finally
• allocate all staff to AllUsers group
• allocate management staff to Mgr group
• allocate payroll staff to Payroll group

64
Read Only View
• A simple way to create a read only view is to add the clause:
With Read Only

to a CREATE VIEW statement.

CREATE VIEW EmpView AS


SELECT empId, empName, emPhoneNo
FROM employee
WITH READ ONLY;

If a user attempts to delete rows from the employee table via EmpView
DELETE FROM EmpView

Then:
Error at line 1:
ORA-42399: cannot perform a DML operation on a read-only view
65
Views – Warning regarding updating tables
• It is possible to
– Insert rows into a view (actually rows are inserted into
the table the view is based on)
– Update rows in a view (ditto)

• Care is needed
– A table may have constraints on some columns where that column
is not in the view
– Example. This table specifies valid values for student gender

Student Table
StuId number Primary Key,
StuName varchar(100),
Gender varchar(1)
CONSTRAINT check_gender CHECK ( Gender IN ('M', 'F', 'I') ) …

66
Updateable & Insertable Views
Create a view based on the Student table
CREATE VIEW STUVIEW
SELECT STUID, STUNAME FROM STUDENT

Create an insert statement based on the view


INSERT INTO STUVIEW (stuid, stuname) values (100, 'Sue Davis');

– Such a statement would fail.


– The gender value (not supplied) does not meet the constraint

• Similar problem(s):
– Inserting data into a View based on joined tables also needs careful thought and
implementation. Tricky!
– Search the topic "Updatable and Insertable Views " for more info…

• This semester, we will avoid the Updatable and Insertable view topic
67
Visio
Drawing ERDs the quick way…

68
Visio – The Quick Way

Microsoft Visio is a drawing package – good for ERDs


• Visio is installed on Lab PCs
• It is available (plus other software) via ELMS https://elms.ict.swin.edu.au/

• To make a good looking ERDs in


Visio you only need to know
a few steps:

• I suggest using the


Blank Drawing template

• AVOID templates for ERDs or


Software and Database
69
Visio – The Quick Way

• To make a simple & good looking ERD in Visio you only need to know
a few steps:

1. The only drawing tools that


are required can be accessed
via the rectangle icon on the
ribbon.

Hint: If you know how to add


those drawing icons to your
customised access toolbar,
then it makes drawing a bit
faster.

70
Visio – The Quick Way

2. Click the rectangle tool


and draw a rectangle

3. To stop drawing rectangles (or any shape)


click the pointer tool on the Ribbon

71
Visio – The Quick Way

4. Double Click rectangle to add text

5. Click the line tool to draw a relationship line


(Draw the line. If the line seems to draw itself at a slight angle,
hold the shift key down as your draw)

6. Double Click the line to


add text (e.g. 'has')

72
Visio – The Quick Way
7. To change the ends of the line:
• Choose Format / Line from menu or
click the line and press Shift F3
• The most common line ends
are 25 & 29.
• Use 20 for Attributes
• Use Jumbo for size

BRANCH Has EMPLOYEE

8. Use the Text Tool to add the attribute name.


Also useful for adding text underneath lines has
73
Visio – The Quick Way

9. Double Borders. One


way to create a double
border is to click on the
offset icon *
Then type 1mm

This creates a triple outline. The outside box is highlighted.


Press Del key to remove the outside (3rd) box.

74
Visio – The Quick Way
Note: The offset icon is not visible via standard menus in Visio!!!

So do the following…:

– Click in the Grey Area of the


Ribbon and choose
Customize Quick Access Toolbar

– Select All Commands


Find the Offset option
Click ADD so its added to the toolbar

75
Visio – The Quick Way

10. Use the Group tool to glue objects together. They can then be 'moved as one'.
Choose UnGroup to edit objects individually.

76
Visio – The Quick Way
To copy the entire ERD Drawing to MS Word:

– Save your work as a Visio drawing (for backup purposes)


– Select All
– Copy
– Open MS Word
– Paste

– The image can be resized etc.

Right Click the image to edit / open the drawing


– Visio must be installed on the computer to open / edit

That's it. Every ERD in INF10002/60009 has used this method.


77
Visio – Using Intelligent Shapes

• Visio drawings can also use 'intelligent' shapes.

An intelligent shape uses connection points to connect shapes


When one shape moves, all connected shapes adjust accordingly

1. Choose View / Task Panes / Shapes / Basic Shapes


2. Place rectangle shape on the drawing
3. Use dynamic connectors to join the shapes

The list of shapes in this window may be


in a different sequence. You can drag
favourite shapes to the top of the list.
78
Visio – Using Intelligent Shapes

• Two rectangle have been drawn.


• Now use the Dynamic connector tool
to draw a line between shapes
• The line snaps to one a the connection point on both shapes

• Either shape can now be moved


• The connection lines are auto-magically redrawn
• Press Shift F3 to change the line ends for cardinality & participation constraints

79
Visio – Using Intelligent Shapes

Image 1 shows a dynamic connector


drawn between Employee and
Department.

Image 2 shows how the connector is


reshaped as the Product entity is dragged
across the diagram

Image 3 shows how the connector is


reshaped again as the Department
entity is dragged to a new location

80
Visio – Using Intelligent Shapes
4. Some rectangles may require
many connection points
(for attributes)

Click on the Connection Tool icon


and select the Connection Point
Tool

5. Hold down the Ctrl Key, and click


on the edge of the rectangle.
Each click creates a new
connection point

• https://support.office.com/en-au/article/Connect-shapes-by-using-AutoConnect-or-the-
Connector-tool-6122a82b-8c1b-4965-b6e1-b15d26f8aab6

81

You might also like