Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 47

Lecture 1

Database Design
(Conceptual – Logical – Physical)
Database Design

Business
specification Entity-Relationship
(Conceptual) model

Tables (Logical)
model Oracle
server

Tables on disk
(Physical model)
Database Conceptual Design:
Entity Relationship (ER) Modelling

• ER modelling: a top-down method used by analysts and


designers for analysing a system’s information requirements.
• UML (Unified Modelling Language): industry standard that
covers the development cycle (analysis, design,
implementation and documentation). For ER modelling, only
one component of UML is used: class diagrams.
• Example of ER model using a UML class diagram:
– Each employee works in one department. A department can have
many employees or none.

EMPLOYEE DEPARTMENT
Works in
ID number
name 0..* 1..1 name
job title location
Entities/Classes

• Entity/Class: A Thing (usually corresponds to a noun)


– Employee works in a Department
• Attributes: Properties of an entity
– Employees have a name and a job title
• Primary Key: Attribute(s) that uniquely identifies each
instance of an entity.
• Notation: EntityName (attribute1, attribute2, …)
• Example: Employee (ID, name, jobtitle)

EMPLOYEE
ID (PK)
name
jobtitle
Relationships
• Relationship: a named association between two
entities (usually corresponds to a verb):
• Each Employee works in a Department
• Three types of Relationship:
• One-to-One, One-to-Many, Many-to-Many
• Notation: Each instance of E1 is related to at least Min
and at most Max instances of E2

E1 E2
Min..Max

• Example: Each employee must work in one department.


Each department may have none or many employees.

EMPLOYEE DEPARTMENT
Works in
ID (PK) number (PK)
name name
job title 0..* 1..1 location
Relationships with Attributes
• A relationship can have its own attributes.
• Example: A student studies many modules. Each
module has many students. For each student and
module, we record the grade, and the date it was
obtained.

grade
date

Student Module
studies
ID (PK) number (PK)
name name
course 0..* 1..* location
Self Relationships
• An entity can have a relationship with itself.
• Example: An employee can supervise many other
employees, but can only be supervised by one
employee.

0..*

Employee
ID (PK) supervises
name
course 1..1
Examples of ER diagrams

borrow
Membe s Boo
r 0..* 0..10 k

teache
Lecture s Modul
r 1.. 0.. e
1 3

studie
Studen s Modul
t 0..* 1.. e
8

Note that only the entities/classes (without attributes) are shown in these examples
Sub Entities/Classes

works_in
staff department
1..* 1..1

researcher admin lecturer


1..*

teaches

1..*

modules
Database Logical Design:
The Relational Model
Relational Database Concept

• Dr. E. F. Codd proposed the relational model for


database systems in 1970.
• It is the basis for the relational database
management system (RDBMS).
• The relational model consists of the following:
– Collection of relations (or tables)
– Set of operators to act on the relations
– Data integrity for accuracy and consistency
• Caution: Relation is a synonym of Table (hence
Relational model) but is different from Relationship
(which is the link between two tables).
Definition of a Relational Database

A relational database is a collection of relations or 2-dimensional tables.

Database

Table name: EMPLOYEES Table name: DEPARTMENTS

… …
Notation: TableName (column1,…, columnN)
PK is underlined
Example: EMPLOYEES(Employee_ID, …, Job_Title)
Relating Multiple Tables
• You can logically relate data from multiple tables using
foreign keys (FK). An FK in a table refers to a PK (or unique
key column) in another table. An FK can have a NULL value.

Table name: DEPARTMENTS


Table name: EMPLOYEES


Primary key Foreign Primary key
key
EMPLOYEES(Employee_ID, First_Name, Last_Name, Dept_ID*)
FK is shown with an asterisk (*)
Relational Database Terminology

Non-key value column) Foreign Key column


3 4
column 2

5 field
NULL

row 1
Transforming ER model to Relational Model

• Each entity/class turns into a table with the same attributes


and primary key.

• Each relationship turns into either:


– A foreign key in one of the two related tables (only if this
foreign key cannot be multi-valued and preferably not NULL);
or
– A table consisting of the two primary keys of the two related
tables + any attributes attached to the relationship
Transforming 1..1 relationships

Project assigned Staff


projID (PK) staffID (PK) Project(projID, pName, staffID, sname)
pName 1..1 1..1 sName

Project assigned Staff


Staff(staffID, sName)
projID (PK) staffID (PK)
pName 0..1 1..1 sName Project(projID, pName, staffID*)

Staff(staffID, sName, projID*)


Project(projID, pName)
Could be
OR
NULL
Staff(staffID, sName)
Project assigned Staff Project(projID, pName, staffID*)
projID (PK) staffID (PK) OR
pName 0..1 0..1 sName
Staff(staffID, sName)
Project(projID, pName)
assigned(staffID*, projID*) PK: either
Transforming 1..N relationships

Project assigned Staff Staff(staffID, sName, projID*)


projID (PK) staffID (PK)
pName 1..1 1..* sName Project(projID, pName)
0..*

Project assigned Staff Staff(staffID, sName, projID*)


projID (PK) staffID (PK)
pName 0..1 1..* sName
0..* Project(projID, pName) Could be
NULL
OR
Staff(staffID, sName)
Project(projID, pName)
assigned(staffID*, projID*)
Transforming M..N relationships

Project assigned Staff Staff(staffID, sName)


projID (PK) staffID (PK)
pName 1..* 1..* sName Project(projID, pName)
0..* 0..* assigned(staffID*, projID*)
Transforming Super/Sub Classes into
Relational Model

Doctor
Staffno (PK)
Roomno
Telno
Date_qualifie
d
{Participation Constraint,
Disjoint constraint}

Surgeon Consultant
specialit specialis
y m
Converting Super/Sub classes into
Relational Model

• There are various options on how to represent such a


relationship as one or more relations. Most appropriate
option dependent on 2 constraints:
• Participation Constraint (Mandatory/Optional):
determines whether every member in the superclass must
participate as member of a subclass
• Disjoint constraint (OR/AND): describes the relationship
between members of the subclasses and whether it is
possible for a member of a superclass to be a member of
one or many subclass(es).
Option 1 – Mandatory, And
Place all attributes in one relation with one or more flags:

Docto
Staffnor(PK)
Roomno
Telno
Date_qualified

{Mandatory, And}

Surgeo Consultan
n
speciality t
specialism

AllDoctors (staffNo, RoomNo, telNo, Date_qualified,


speciality, specialism, surgeonFlag, consultantFlag)
Option 2 – Optional, And

2 Relations, one for superclass and one for all subclasses.

Docto
Staffnor(PK)
Roomno
Telno
Date_qualified

Optional, And}

Surgeo Consultan
n
speciality t
specialism

Doctor (staffNo, RoomNo, telNo, Date_qualified)


SurgCon (staffNo*, speciality, specialism, surgeonFlag, consultantFlag)
Option 3 – Mandatory, Or

One relation for each combined superclass/subclass


Docto
Staffnor(PK)
Roomno
Telno
Date_qualified

{Mandatory, Or}

Surgeo Consultan
n
speciality t
specialism

Surgeon (staffNo, RoomNo, telNo, Date_qualified, speciality)


Consultant (staffNo, RoomNo, telNo, Date_qualified, specialism)
Option 4 – Optional, Or

One relation for superclass and one for each subclass

Docto
Staffnor(PK)
Roomno
Telno
Date_qualified

Optional, Or

Surgeo Consultan
n
speciality t
specialism

Doctor (staffNo, RoomNo, telNo, Date_qualified)


Surgeon (staffNo*, speciality)
Consultant (staffNo*, specialism)
Normalisation

A technique for producing a set of relations with desirable properties,


given the data requirements of an enterprise.
Anomalies that may arise in a un-normalised database
Example: Staff working at various company branches:
Staff_Branch(staffNo, sName, branchNo, bAddress)
staffNo sName branchNo bAddress

S1 Smith B5 King St
S2 Kumar B5 King St
S3 Brown B1 Union St
Insertion anomaly: new member of staff added, but branch
address mistyped. Now have conflicting data.
Also, can’t add a new branch unless a staff is added.
Deletion anomaly: all staff of branch number 5 deleted -
branch 5 details are now missing.
Update anomaly: branch address changes. Needs to be
changed in all rows where it appears in the table. If not all
changes are made correctly, conflicting data results.
1st Normal Form (1NF)

• A table is in 1NF if each field contains only one value (no


attribute or group of attributes are allowed to have multiple
values for a single occurrence of the primary key).

Example1: Staff(staffNbr, name, (Telephones) ),


This is not allowed because (Telephones) is a list of thelephones
• SolutionA: Staff(staffNbr, name, Tel1, Tel2, Tel3)
• SolutionB: Staff(staffNbr, name), StaffTel(StaffNbr*, Tel)

Example2: Staff( staffNbr, name, (Qual, Date) ),


Solution: Remove the repeating group of attributes, into a
new table. Add the original PK to table and choose a PK.
Staff(staffNbr, name)
Staff_Qualifications(staffNbr*, Qual, Date)
2nd Normal Form

• A relation is in 2NF if it’s in 1NF and every column (which


is not part of the PK) is fully dependent on the PK, i.e.
there are no partial dependencies.

• Example: If Table1(A, B, C, D) and B 🡪 C then C is not


fully dependent on the PK (A, B)

• Solution: Identify the partial dependencies and


separate them into their own tables:
Table1(A, B*, D) and Table2(B, C)

• Note: A 1NF relation with a non-composite key is


automatically in 2NF
2ND Normal Form - Example

Orders(orderNo, partNo, partDescription, unitPrice, quantity)

orderNo partNo partDescr partPrice quantity

OR1 P23 Laptop 250 2


OR1 P14 Mouse 10 5
OR2 P23 Laptop 250 4

orderno, partno → quantity


partNo → partDescription, unit-price (Partial Dependencies)

Solution:
Part(partNo, partDescription, unitPrice)
Order(orderNo, partNo*, quantity)
3rd Normal Form

• A relation is in 3NF if it’s in 2NF and there are no


transitive dependencies.

• Example: Table1(A, B, C, D) C is said to be transitively


dependent on A if A 🡪 B and B 🡪 C (ie A 🡪 C via B)

• Solution: Identify the transitive dependencies and


separate them into their own tables:
Table1(A, B*, D) and Table2(B, C)
3rd Normal Form - Example

Order( orderNo, supplierNo, supplierName, supplierAddress, orderDate)

orderNo suppNo suppName suppAddr orderDate

OR1 S23 Smith Aberdeen 20-Sep-12

OR2 S23 Smith Aberdeen 25-Sep-12


OR3 S15 Ali Glasgow 25-Sep-12

orderNo 🡪 supplierNo
supplierNo 🡪 supplierName, supplierAddress

Solution:
Order( orderNo, supplierNo*, orderDate)
supplier(supplierNo, supplierName, supplierAddress)
Database Physical Design:
Creating Tables in Oracle Database
Database Objects
Object Description
Table Basic unit of storage; composed of rows
View Logically represents subsets of data from one or more tables

Sequence Generates numeric values


Index Improves the performance of some queries

Synonym Gives alternative names to objects

Naming Rules for Table names and column names:


• Must begin with a letter
• Must be 1–30 characters long
• Must contain only A–Z, a–z, 0–9, _, $, and #
• Must not duplicate the name of another object owned by
the same user
• Must not be an Oracle server–reserved word
CREATE TABLE Statement
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr][, ...]);

Example:

CREATE TABLE dept


(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13),
create_date DATE DEFAULT SYSDATE);
Data Types

Data Type Description


VARCHAR2(size) Variable-length character data
CHAR(size) Fixed-length character data
NUMBER(p,s) Variable-length numeric data
DATE/TIMESTAMP Date and time values
LONG Variable-length character data (up to 2 GB)
CLOB Character data (up to 4 GB)
RAW and LONG Raw binary data
RAW
BLOB Binary data (up to 4 GB)
BFILE Binary data stored in an external file (up to 4 GB)
ROWID A base-64 number system representing the unique
address of a row in its table
Constraints

• Constraints enforce rules at the table level.


• The following constraint types are valid:
– NOT NULL
– UNIQUE
– PRIMARY KEY
– FOREIGN KEY
– CHECK

• You can name a constraint, or Oracle generates a name by


using the SYS_Cn format.
• Create a constraint at either of the following times:
– At the same time as the table is created
– After the table has been created
• Define a constraint at the column or table level.
Defining Constraints
• Syntax:
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr]
[column_constraint],
...
[table_constraint][,...]);
• Column-level constraint:
column [CONSTRAINT constraint_name]
constraint_type,
• Table-level constraint:
column,...
[CONSTRAINT constraint_name] constraint_type
(column, ...),
Defining Constraints - Example

• Column-level constraint:
CREATE TABLE employees(
employee_id NUMBER(6)
CONSTRAINT emp_emp_id_pk PRIMARY KEY,
first_name VARCHAR2(20),
...);

• Table-level constraint:

CREATE TABLE employees(


employee_id NUMBER(6),
first_name VARCHAR2(20),
...
job_id VARCHAR2(10) NOT NULL,
CONSTRAINT emp_emp_id_pk PRIMARY KEY (EMPLOYEE_ID));
NOT NULL - UNIQUE - CHECK Constraints

UNIQUE CHECK (salary > 0)

NOT NULL Absence of NOT NULL


constraint
(can contain a null
value)
FOREIGN KEY Constraint

DEPARTMENTS

PRIMARY
KEY

EMPLOYEES
FOREIGN
KEY

… Not allowed
INSERT INTO (9 does not
exist)
Allowed
FOREIGN KEY Constraint - Example
CREATE TABLE employees(
employee_id NUMBER(6),
last_name VARCHAR2(25) NOT
NULL,
email VARCHAR2(25),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
hire_date DATE NOT NULL,
department_id NUMBER(4),
CONSTRAINT emp_dept_fk FOREIGN KEY
(department_id)
REFERENCES
departments(department_id),
CONSTRAINT emp_email_uk
UNIQUE(email));

• FOREIGN KEY: Defines the column in the child table at the table-
constraint level
• REFERENCES: Identifies the table and column in the parent table
• ON DELETE CASCADE: Deletes the dependent rows in the child table
when a row in the parent table is deleted
• ON DELETE SET NULL: Converts dependent foreign key values to null
CREATE TABLE: Example
CREATE TABLE employees (
employee_id NUMBER(6)
CONSTRAINT emp_employee_id PRIMARY KEY,
first_name VARCHAR2(20),
last_name VARCHAR2(25)
CONSTRAINT emp_last_name_nn NOT NULL,
email VARCHAR2(25)
CONSTRAINT emp_email_nn NOT NULL
CONSTRAINT emp_email_uk UNIQUE,
phone_number VARCHAR2(20),
hire_date DATE
CONSTRAINT emp_hire_date_nn NOT NULL,
job_id VARCHAR2(10)
CONSTRAINT emp_job_nn NOT NULL,
salary NUMBER(8,2)
CONSTRAINT emp_salary_ck CHECK (salary>0),
commission_pct NUMBER(2,2),
manager_id NUMBER(6),
department_id NUMBER(4)
CONSTRAINT emp_dept_fk REFERENCES
departments (department_id));
ALTER TABLE Statement

Use the ALTER TABLE statement to:


• Add a new column: ALTER TABLE emp ADD (job_id VARCHAR2(7));
• Modify an existing column: ALTER TABLEemp MODIFY (job_id
VARCHAR2(9));
• Drop a column: ALTER TABLE emp DROP COLUMN job_id;
• Add a constraint: ALTER TABLE emp2 ADD CONSTRAINT min_salary
CHECK(salary > 0);
• Drop a constraint: ALTER TABLE emp2 DROP CONSTRAINT min_salary;
• Disable/Enable a constraint: ALTER TABLE emp2 DISABLE/ENABLE
CONSTRAINT min_salary;
Drop Statement

• All data and structure in the table are deleted.


• Any pending transactions are committed.
• All indexes/constraints are dropped.
• You cannot roll back.

DROP TABLE emp;

TRUNCATE Statement
• TRUNCATE removes all rows from a table, leaving the
table empty and the table structure intact (faster than
DELETE statement)

TRUNCATE TABLE copy_emp;


INSERT statement
• inserting only one row:
INSERT INTO departments VALUES (70, 'Public Relations');

INSERT INTO departments(department_id, department_name)


VALUES (70, 'Public Relations');

• inserting special values:

INSERT INTO employees (employee_id, hire_date, tel)


VALUES(113, SYSDATE, NULL);
INSERT INTO employees (employee_id, hire_date)
VALUES(114, TO_DATE(‘SEP 3, 2012', 'MON DD,
YYYY'));
• inserting rows from another table:

INSERT INTO sales_reps(id, name, salary, comm_pct)


SELECT employee_id, last_name, salary, commission_pct
FROM employees WHERE job_id LIKE '%REP%';
UPDATE Statement
• Specific rows are modified if you specify the WHERE clause:
UPDATE employees
SET department_id = 70
WHERE employee_id = 113;
• All rows are modified if you omit the WHERE clause:
UPDATE copy_emp
SET department_id = 110;

• Updating two columns with subqueries: Update employee


114’s job and salary to match that of employee 205:
UPDATE employees
SET job_id = (SELECT job_id
FROM employees
WHERE employee_id = 205),
salary = (SELECT salary
FROM employees
WHERE employee_id = 205)
WHERE employee_id = 114;
DELETE Statement

• Specific rows are deleted if you specify the WHERE clause:


DELETE FROM departments
WHERE department_name = 'Finance';

• All rows in the table are deleted if you omit the WHERE clause:

DELETE FROM copy_emp;

Use subqueries to remove rows based on values from


another table:
DELETE FROM employees
WHERE department_id =
(SELECT department_id
FROM departments
WHERE department_name
LIKE '%Public%');

You might also like