Professional Documents
Culture Documents
By
Dr Salman Naseer Adil
PhD in Computer and Information Sciences
Product
Planning Control Sales
Development
Corporate
Database
Accounting Manufacturing
Accounts Accounts
Scheduling Production
Receivable Payable
A bit of History
• Computer initially used for computational/
engineering purposes
• Commercial applications introduced File Processing
System
File Processing System
• A collection of programs that perform
services for the end-users such as production of
reports
File Processing Systems
Grade Class
Duplication of Data
Vulnerable to Inconsistency
Advantages of Database Approach
Library Examination Registration
Database
Management
System
• Is Data
• A Resource ? ? ?
Levels of Data
• Real-world data
• Metadata
• Data Occurrence
Database Users
• Application Programmers
• End Users
• Naïve
• Sophisticated
Database Users
• Database Administrator (DBA)
• A person who has central control over data
and programs that access this data
Functions of DBA
Schema definition
Granting data access
Functions of DBA
Routine Maintenance
Backups
Monitoring disk space
Monitoring jobs running
Data, Database, Data Model and DBMS
End users
Software interact
DBMS Database
maintain Administrators
“How” to get
Data
Database
design Designers
Database
Users
Common Terms
• Data
• Information
• Database Management system (DBMS)
Common Terms
• Data: Facts concerning things, such as people,
objects, or events
Common Terms
• Information: Data that have been processed and presented
in a form suitable for human interpretation
Data, Information and Knowledge
an g irTah Database
Amir Shoes Amir is most
Jah ira Queries
Mohsin
Tahira
Scarves
Jewelry ?
likely to buy new
product
wi Jahangir Groceries
re
Am Ma
00
le
Te
4 ss
23
50,0
d
ex rtin
r
Ami
B.A.
Go
Data Independence
Database Architecture
Three Level Architecture
Conceptual Conceptual
Level Schema
Internal
Internal Level
Schema
Physical Data
Organization Database
Level 1
External View
External Layer
Lower Layers
Level 2
Logical or Conceptual View
Ext/Con Mapping
Conceptual Level Conceptual
Schema
Con/Int Mapping
Internal
Internal Level
Schema
Physical Data
Organization Database
First Name: Rana Name: R. Aslam
Last Name: Aslam Saleema Age: 24y,10d
Date of Birth: Dept: Sales
12 Sep, 1970
Saleem
01110011010011100101001010100101010010101…..
Data Independence
Data Independence
A major outcome of 3-L Arch
The immunity of applications to change in storage structure
and access strategy
Data Independence
Changes in lower level do not affect the upper levels
Don’t take it word to word
Mind the direction please
Data Independence Types
Physical Data
Organization Database
Functions of DBMS
Data Processing
A User Accessible Catalog
Transaction Support
Concurrency Control Services
Functions of DBMS
Recovery Services
Authorization Services
Support for Data Communication
Integrity Services
DBMS Environments
Single User
Multi-user
Teleprocessing
File Servers
Client-Server
Teleprocessing
All processing at
a central computer
Dumb Terminals
File Servers
File Server
Database
LAN
Workstation Workstation
Client-Server
Server
Database (with DBMS)
LAN
Client Client
Introduction to Relational Data
Model
Two Major Strengths
Simplicity
• PREDICATE(RELATION)
Select
• To process a selection,
• Look at each tuple
• See if we have a match (based on the condition)
Select
Course2
CID ProgID Cred_Hrs CourseTitle
Course 1 U Course 2
CID ProgID Cred_Hrs CourseTitle
Course 1 ⋂ Course
2
CID ProgID Cred_Hrs CourseTitle
Course1 – Course2
CID ProgID Cred_Hrs CourseTitle
• Course X Registration
Course Registration
CID CourseTitle SID StudName
R S
Theta Join Example
FACULTY COURSE
F3456 Tahir CSE 23000 Asso Prof C3456 Database Systems F2345
F3456 Tahir CSE 23000 Asso Prof C5678 Money & Capital Market F4567
F4567 Ayesha ENG 27000 Asso Prof C3456 Database Systems F2345
F4567 Ayesha ENG 27000 Asso Prof C5678 Money & Capital Market F4567
F4567 Ayesha ENG 27000 Asso Prof C5678 Money & Capital Market F4567
F4567 Ayesha ENG 27000 Asso Prof C5678 Money & Capital Market F4567
F4567 Ayesha ENG 27000 Asso Prof C5678 Money & Capital Market
F4567 Ayesha ENG 27000 Asso Prof Money & Capital Market
C5678 F4567
. To Accounting
F4567 Ayesha ENG 27000 Asso Prof Money & Capital Market F4567
C5678 Money & Capital Market
.
F4567 Ayesha ENG 27000 Asso Prof Money & Capital Market F4567
C5678 Money & Capital Market
.
FACULTY COURSE
Semijoin Example
FACULTY COURSE
facId facName dept salary rank
Table 1 Table 1
Join
Table 1 Table 2
Basic SELECT Statement
SELECT [DISTINCT] {*, column [alias],...}
FROM table;
DEPTNO LOC
--------- -------------
10 NEW YORK
20 DALLAS
30 CHICAGO
40 BOSTON
Column Heading Defaults
• Default justification
• Left: Date and character data
• Right: Numeric data
• Default display: Uppercase
Arithmetic Expressions
• Create expressions on NUMBER and DATE data by
using arithmetic operators.
Operator Description
+ Add
- Subtract
* Multiply
/ Divide
Using Arithmetic Operators
SQL> SELECT ename, sal, sal+300
2 FROM emp;
ENAME 12*SAL+COMM
---------- -----------
KING
Defining a Column Alias
• Renames a column heading
• Is useful with calculations
• Immediately follows column name; optional AS
keyword between column name and alias
• Requires double quotation marks if it contains
spaces or special characters or is case sensitive
Using Column Aliases
SQL> SELECT ename AS name, sal salary
2 FROM emp;
NAME SALARY
------------- ---------
...
Employees
-------------------
KINGPRESIDENT
BLAKEMANAGER
CLARKMANAGER
JONESMANAGER
MARTINSALESMAN
ALLENSALESMAN
...
14 rows selected.
Literal Character Strings
• A literal is a character, expression, or number
included in the SELECT list.
• Date and character literal values must be enclosed
within single quotation marks.
• Each character string is output once for each row
returned.
Using Literal Character Strings
SQL> SELECT ename ||' '||'is a'||' '||job
2 AS "Employee Details"
3 FROM emp;
Employee Details
-------------------------
KING is a PRESIDENT
BLAKE is a MANAGER
CLARK is a MANAGER
JONES is a MANAGER
MARTIN is a SALESMAN
...
14 rows selected.
Duplicate Rows
• The default display of queries is all rows,
including duplicate rows.
SQL> SELECT deptno
2 FROM emp;
DEPTNO
---------
10
30
10
20
...
14 rows selected.
Eliminating Duplicate Rows
Eliminate duplicate rows by using the DISTINCT keyword in the
SELECT clause.
DEPTNO
---------
10
20
30
Logging In to SQL
• From Windows environment:
DESC[RIBE] tablename
Displaying Table Structure
SQL> DESCRIBE dept
EMP
EMPNO ENAME JOB ... DEPTNO
= Equal to
ENAME SAL
---------- --------- Lower Higher
MARTIN 1250 limit limit
TURNER 1500
WARD 1250
ADAMS 1100
MILLER 1300
Using the IN Operator
• Use the IN operator to test for values in a list.
ENAME
• You can use the ESCAPE identifier to search for "%" or
----------
"_".
MARTIN
JAMES
WARD
Using the IS NULL Operator
• Test for null values with the IS NULL operator.
ENAME MGR
---------- ---------
KING
Logical Operators
Operator Meaning
ENAME JOB
---------- ---------
KING PRESIDENT
MARTIN SALESMAN
ALLEN SALESMAN
TURNER SALESMAN
WARD SALESMAN
Rules of Precedence
Order Evaluated Operator
1 All comparison
operators
2 NOT
3 AND
4 OR
ENAME DNAME
------ ----------
KING ACCOUNTING
“Cartesian BLAKE ACCOUNTING
product: ...
KING RESEARCH
14*4=56 rows” BLAKE RESEARCH
...
56 rows selected.
Types of Joins
Equijoin Non-equijoin Outer join Self join
What Is an Equijoin?
EMP DEPT
EMPNO ENAME DEPTNO DEPTNO DNAME LOC
------ ------- ------- ------- ---------- --------
7839 KING 10 10 ACCOUNTING NEW YORK
7698 BLAKE 30 30 SALES CHICAGO
7782 CLARK 10 10 ACCOUNTING NEW YORK
7566 JONES 20 20 RESEARCH DALLAS
7654 MARTIN 30 30 SALES CHICAGO
7499 ALLEN 30 30 SALES CHICAGO
7844 TURNER 30 30 SALES CHICAGO
7900 JAMES 30 30 SALES CHICAGO
7521 WARD 30 30 SALES CHICAGO
7902 FORD 20 20 RESEARCH DALLAS
7369 SMITH 20 20 RESEARCH DALLAS
... ...
14 rows selected. 14 rows selected.
No employee in the
OPERATIONS department
Outer Joins
• You use an outer join to also see rows that do not
usually meet the join condition.
• Outer join operator is the plus sign (+).
WORKER.ENAME||'WORKSFOR'||MANAG
-------------------------------
BLAKE works for KING
CLARK works for KING
JONES works for KING
MARTIN works for BLAKE
...
13 rows selected.
Summary
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column1 = table2.column2;
MIN(HIRED MAX(HIRED
--------- ---------
17-DEC-80 12-JAN-83
Using the COUNT Function
• COUNT(*) returns the number of rows in a table.
COUNT(*)
---------
6
Using the COUNT Function
• COUNT(expr) returns the number of nonnull
rows.
SQL> SELECT COUNT(comm)
2 FROM emp
3 WHERE deptno = 30;
COUNT(COMM)
-----------
4
Group Functions and Null Values
• Group functions ignore null values in the
column.
SQL> SELECT AVG(comm)
2 FROM emp;
AVG(COMM)
---------
550
Using the NVL Function
with Group Functions
• The NVL function forces group functions to
include null values.
AVG(NVL(COMM,0))
----------------
157.14286
Creating Groups of Data
EMP
DEPTNO SAL
--------- ---------
10 2450
10 5000 2916.6667
10 1300
20 800 “average DEPTNO AVG(SAL)
20 1100 salary
------- ---------
20 3000 2175 in EMP
20 3000 table 10 2916.6667
20 2975 for each 20 2175
30 1600 department” 30 1566.6667
30 2850
30 1250 1566.6667
30 950
30 1500
30 1250
Creating Groups of Data:
GROUP BY Clause
DEPTNO AVG(SAL)
--------- ---------
10 2916.6667
20 2175
30 1566.6667
Using the GROUP BY Clause
• The GROUP BY column does not have to be in the
SELECT list.
SQL> SELECT AVG(sal)
2 FROM emp
3 GROUP BY deptno;
AVG(SAL)
---------
2916.6667
2175
1566.6667
Grouping by More
Than
EMP
One Column
DEPTNO JOB SAL
--------- --------- ---------
10 MANAGER 2450
DEPTNO JOB SUM(SAL)
10 PRESIDENT 5000
-------- --------- ---------
10 CLERK 1300
10 CLERK 1300
20 CLERK 800 “sum salaries in 10 MANAGER 2450
20 CLERK 1100 the EMP table
10 PRESIDENT 5000
20 ANALYST 3000 for each job,
20 ANALYST 6000
20 ANALYST 3000 grouped by
20 CLERK 1900
20 MANAGER 2975 department”
20 MANAGER 2975
30 SALESMAN 1600
30 CLERK 950
30 MANAGER 2850
30 MANAGER 2850
30 SALESMAN 1250
30 SALESMAN 5600
30 CLERK 950
30 SALESMAN 1500
30 SALESMAN 1250
Using the GROUP BY Clause
on Multiple Columns
SQL> SELECT deptno, job, sum(sal)
2 FROM emp
3 GROUP BY deptno, job;
DEPTNO MAX(SAL)
--------- ---------
10 5000
20 3000
Using the HAVING Clause
SQL> SELECT job, SUM(sal) PAYROLL
2 FROM emp
3 WHERE job NOT LIKE 'SALES%'
4 GROUP BY job
5 HAVING SUM(sal)>5000
6 ORDER BY SUM(sal);
JOB PAYROLL
--------- ---------
ANALYST 6000
MANAGER 8275
Nesting Group Functions
• Display the maximum average salary.
MAX(AVG(SAL))
-------------
2916.6667
Summary
SELECT column, group_function(column)
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
Main Query
Subquery
?
“What is Jones’ salary?”
Subqueries
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
ENAME
----------
KING
FORD
SCOTT
Guidelines for Using Subqueries
• Enclose subqueries in parentheses.
• Place subqueries on the right side of the comparison
operator.
• Do not add an ORDER BY clause to a subquery.
• Use single-row operators with single-row
subqueries.
• Use multiple-row operators with multiple-row
subqueries.
Types of Subqueries
• Single-row subquery
Main query
returns
Subquery CLERK
• Multiple-row subquery
Main query
Subquery
returns CLERK
MANAGER
• Multiple-column subquery
Main query
returns
Subquery CLERK 7900
MANAGER 7698
Single-Row Subqueries
• Return only one row
• Use single-row comparison operators
Operator Meaning
= Equal to
ENAME JOB
---------- ---------
MILLER CLERK
Using Group Functions
in a Subquery
SQL> SELECT ename, job, sal
800
2 FROM emp
3 WHERE sal =
4 (SELECT MIN(sal)
5 FROM emp);
no rows selected
Will This Statement Work?
SQL> SELECT ename, job
2 FROM emp
3 WHERE job =
4 (SELECT job
5 FROM emp
6 WHERE ename='SMYTHE');
lue s
o va
n s n
no rows selected
et ur
r y r
qu e
Sub
Multiple-Row Subqueries
• Return more than one row
• Use multiple-row comparison operators
Operator Meaning
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
Practice Overview
• Creating subqueries to query values based on unknown criteria
• Using subqueries to find out what values exist in one set of data and not in another
Multiple-Column
Subqueries
By
Prof. Salman Naseer Adil
Objectives
• After completing this lesson, you should be able
to do the following:
• Write a multiple-column subquery
• Describe and explain the behavior of subqueries
when null values are retrieved
• Write a subquery in a FROM clause
Multiple-Column Subqueries
Main query
MANAGER 10
Subquery
SALESMAN 30
MANAGER 10
CLERK 20
SALESMAN 30
MANAGER 10
MANAGER 10
CLERK 20
Using Multiple-Column Subqueries
Pairwise Nonpairwise
PRODID QTY PRODID QTY
101863 100 101863 100
100861 100 100861 100
102130 10 102130 10
100890 5 100890 5
100870 500 100870 500
101860 50 101860 50
Nonpairwise Comparison
Subquery
• Display the order number, product number, and
quantity of any item in which the product number and
quantity match any product number and any quantity of
an item in order 605.
1 row created.
Creating a Script
with Customized Prompts
• ACCEPT stores the value in a variable.
• PROMPT displays your customized text.
EMP
EMPNO ENAME JOB ... DEPTNO
UPDATE table
SET column = value [, column = value, ...]
• Update
[WHERE more than one row at a time, if required.
condition];
Updating Rows in a Table
• Specific row or rows are modified when you specify
the WHERE clause.
ROLLBACK to Savepoint B
ROLLBACK to Savepoint A
ROLLBACK
Implicit Transaction Processing
• An automatic commit occurs under the following
circumstances:
• DDL statement is issued
• DCL statement is issued
• Normal exit from SQL*Plus, without explicitly issuing
COMMIT or ROLLBACK
• An automatic rollback occurs under an abnormal
termination of SQL*Plus or a system failure.
State of the Data Before
COMMIT or ROLLBACK
• The previous state of the data can be recovered.
• The current user can review the results of the DML
operations by using the SELECT statement.
• Other users cannot view the results of the DML statements
by the current user.
• The affected rows are locked; other users cannot change
the data within the affected rows.
State of the Data After COMMIT
• Data changes are made permanent in the database.
• The previous state of the data is permanently lost.
• All users can view the results.
• Locks on the affected rows are released; those rows are
available for other users to manipulate.
• All savepoints are erased.
Committing Data
• Make the changes.
SQL> UPDATE emp
2 SET deptno = 10
3 WHERE empno = 7782;
1 row updated.
SQL> UPDATE...
SQL> SAVEPOINT update_done;
Savepoint created.
SQL> INSERT...
SQL> ROLLBACK TO update_done;
Rollback complete.
Statement-Level Rollback
• If a single DML statement fails during execution,
only that statement is rolled back.
• The Oracle Server implements an implicit savepoint.
• All other changes are retained.
• The user should terminate transactions explicitly by
executing a COMMIT or ROLLBACK statement.
Read Consistency
• Read consistency guarantees a consistent view of
the data at all times.
• Changes made by one user do not conflict with
changes made by another user.
• Read consistency ensures that on the same data:
• Readers do not wait for writers
• Writers do not wait for readers
Implementation of Read
Consistency
UPDATE emp Data
SET sal = 2000 blocks
WHERE ename =
'SCOTT';
Rollback
segments
User A
changed
SELECT * and unchanged
FROM emp; Read data
consistent
image before
change
“old” data
User B
Locking
• Oracle locks:
• Prevent destructive interaction between concurrent
transactions
• Require no user action
• Automatically use the lowest level of restrictiveness
• Are held for the duration of the transaction
• Have two basic modes:
• Exclusive
• Share
Summary
Statement Description
Object Description
Table Basic unit of storage; composed of rows
and columns
View Logically represents subsets of data from
one or more tables
Sequence Generates primary key values
Index Improves the performance of some queries
Synonym Gives alternative names to objects
Naming Conventions
• Must begin with a letter
• Can 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
The CREATE TABLE Statement
• You must have :
• CREATE TABLE privilege
• A storage area
• You TABLE
CREATE specify:
[schema.]table
(column datatype [DEFAULT expr][, ...]);
• Table name
• Column name, column datatype, and column size
Referencing Another User’s
Tables
• Tables belonging to other users are not in the user’s
schema.
• You should use the owner’s name as a prefix to the
table.
The DEFAULT Option
• Specify a default value for a column during an insert.
SQL> RENAME
• You dept
must be theTOowner
department;
of the object.
Table renamed.
Truncating a Table
• The TRUNCATE TABLE statement:
• Removes all rows from a table
• Releases the storage space used by that table
Statement Description
CREATE TABLE Creates a table
ALTER TABLE Modifies table structures
DROP TABLE Removes the rows and table structure
RENAME Changes the name• of a table, view,
sequence, or synonym
TRUNCATE Removes all rows from a table and
releases the storage space
•
COMMENT Adds comments to a table or view
•
Practice Overview
• Creating new tables
• Creating a new table by using the CREATE TABLE AS syntax
• Modifying column definitions
• Verifying that the tables exist
• Adding comments to a tables
• Dropping tables
• Altering tables
Including Constraints
By
Prof. Salman Naseer Adil
Objectives
• After completing this lesson, you should be able
to do the following:
• Describe constraints
• Create and maintain constraints
What Are Constraints?
• Constraints enforce rules at the table level.
• Constraints prevent the deletion of a table if there are
dependencies.
• The following constraint types are valid in Oracle:
• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
• CHECK
Constraint Guidelines
• Name a constraint or the Oracle Server will generate a
name by using the SYS_Cn format.
• Create a constraint:
• At the same time as the table is created
• After the table has been created
• Define a constraint at the column or table level.
• View a constraint in the data dictionary.
Defining Constraints
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr]
[column_constraint],
...
[table_constraint][,...]);
column,...
[CONSTRAINT constraint_name] constraint_type
(column, ...),
The NOT NULL Constraint
• Ensures that null values are not permitted for
the column
EMP
EMPNO ENAME JOB ... COMM DEPTNO
CONSTRAINT_NAME C SEARCH_CONDITION
------------------------ - -------------------------
SYS_C00674 C EMPNO IS NOT NULL
SYS_C00675 C DEPTNO IS NOT NULL
EMP_EMPNO_PK P
...
Viewing the Columns Associated
with Constraints
• View the columns associated with the constraint
names in the USER_CONS_COLUMNS view.
CONSTRAINT_NAME COLUMN_NAME
------------------------- ----------------------
EMP_DEPTNO_FK DEPTNO
EMP_EMPNO_PK EMPNO
EMP_MGR_FK MGR
SYS_C00674 EMPNO
SYS_C00675 DEPTNO
Summary
• Create the following types of constraints:
• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
• CHECK
• Query the USER_CONSTRAINTS table to view all constraint
definitions and names.
Practice Overview
• Adding constraints to existing tables
• Adding more columns to a table
• Displaying information in data dictionary views
Creating Views
By
Prof. Salman Naseer Adil
Objectives
• After completing this lesson, you should be able
to do the following:
• Describe a view
• Create a view
• Retrieve data through a view
• Alter the definition of a view
• Insert, update, and delete data through
a view
• Drop a view
Database Objects
Object Description
EMPNO 7876
7499 ADAMS
ENAMEALLEN SALESMAN
CLERK
JOB 7788
7698 12-JAN-83
20-FEB-81 1600
1100 300 30
20
------ 7369
--------
7844 SMITH -----------
TURNER SALESMAN
CLERK 7902
7698 17-DEC-80
08-SEP-81 1500
800 0 30
20
7902
7900 FORD
JAMES CLERK
ANALYST 7566
7698 03-DEC-81 3000
950 30
20
7839 7698
KING
7521 BLAKE
WARD
PRESIDENT
SALESMAN
MANAGER 7839
7698 01-MAY-81
22-FEB-81 1250
2850 500 30
30
7782 7654
CLARK
7902 MARTIN
FORD MANAGER
ANALYST
SALESMAN 7698
7566 28-SEP-81
03-DEC-81 3000
1250 1400 20
30
7934 7499
MILLER
7369 ALLEN
SMITH
CLERK
CLERK
SALESMAN 7698
7902 20-FEB-81
17-DEC-80 1600
800 300 20
30
7844
7788 TURNER
SCOTT ANALYST
SALESMAN 7698
7566 08-SEP-81
09-DEC-82 3000
1500 0 20
30
7900
7876 JAMES
ADAMS CLERK
CLERK 7698
7788 03-DEC-81
12-JAN-83 1100
950 20
30
7521
7934 WARD
MILLER CLERK
SALESMAN 7698
7782 22-FEB-81
23-JAN-82 1300
1250 500 10
30
Why Use Views?
• To restrict database access
• To make complex queries easy
• To allow data independence
• To present different views of the same data
Simple Views
and Complex Views
• Feature Simple Views Complex Views
6 rows selected.
Querying a View
SQL*Plus
USER_VIEWS
SELECT *
EMPVU10
FROM empvu10;
SELECT empno, ename, job
FROM emp
WHERE deptno = 10;
7839 KING PRESIDENT
7782 CLARK MANAGER EMP
7934 MILLER CLERK
Modifying a View
• Modify the EMPVU10 view by using CREATE OR
REPLACE VIEW clause. Add an alias for each column
name.
Users
Manager
Privileges
Physical Design
Implementation
Maintenance
Design Stages
Analyze User Environment
Choose DBMS
Implement System
Test System
Operational Maintenance
Analyze Existing
System
• Objective: To understand the working of existing
system
• Analyze users’ requirements
Entity-Relationship Data Model
E-R Data Model
A semantic data model, used for the graphical
representation of the conceptual database design
Major Components
• Entities
• Attributes
• Relationships
Entity
• Term used to mean three different meanings
• Entity type
• Entity instance
• Entity set
Entity Type
• A name/label assigned to items/objects
that exist in an environment and that
have similar properties
• It could be person, place, event or even
concept
Entity Type
• Distinguishable from other entity types on the basis of
properties
• Identified through abstraction process
• Different from External Entity
Entity Instance & Set
• A particular object belonging to a particular entity type
• Entity Type: Employee
• Entity Instance: M. Sharif
• Entity Set: All employees
Types of Entity Types
EMPPLOYEE DEPENDENTS
BOOK BOOKCOPY
Attribute
An attribute of an entity type is a defining property or quality
of the instances of that entity type. Entity instances of same
entity type have the same attributes. (e.g. Student
Identification, Student Name)
Domain of an Attribute
• Every attribute has a domain
• Set of possible values for an attribute
• The attributes in an entity set get the values from the
same domain
Types of Attributes
• Single vs composite
• Single valued vs multi-valued
• Stored vs derived
Symbols for Attributes
• Each represented as an oval, linked with an ET symbol
Symbols for Attributes
Simple
Composite
Multi-valued
Derived
Example
Experience empId empName
EMPLOYEE address
DEPT EMP
STD BOOK
Relationships
• Relationship type can be identified like an entity type
• A relationship type is an abstraction of a relationship
Relationships
• Entities involved in a relationship are called its participants
• Types of the relationships can be established on the basis of
participant ETs
Relationships Types
A Binary relationship is the one that links two entity types
e.g. STUDENT-CLASS
Binary Relationship Example
STD COURSE
STD BOOK
PROJ EMP
Binary Relationships
• May also have instances, that can be formally described in
an ordered pair form
• {(S1001, OS), (S1020, DS), (S1002, DS), (S1058, NW)}
Attributes of the Rships
• The key
• The relationships can have their descriptive
attributes
• Where to place
Attributes of Rships
GRADE
STD COURSE
Ternary Relationships
• One that involves three entity types
• STUDENT-CLASS-FACULTY
Ternary Relationship Examples
STD COURSE
FACULTY
PROJ EMP
SKILL
Ternary Relationships
• Instances in ordered triples
• Example {(S1013, MCS4, Adnan), (S1023, MCS3,
Fasih)}
Unary Relationship
• An ET linked with itself, also called recursive
relationship
• Example Roommate, where STUDENT is linked with
STUDENT
Unary Relationship Examples
STD ROOMMATE
EMP CHAIR-PERSON
EMP SPOUSE
Cardinality of Rships
Number of instances of one entity type that can
possibly be related to instances of other entity type
Types of Cardinalities
• One to one
• One to many
• Many to one
• Many to many
Types of Cardinalities
One to one
Chair
DEPT
Person
Many to many
EMP PROJ
EMP PROJ
Minimum Cardinality
• Determines whether the link is compulsory or
optional
• Important, since it effects the implementation
Cardinality Example
STD BOOK
EMP PROJ
STD COURSE
STD HOBBY
Other Notations
STD BOOK
STD HOBBY
PROJ EMP
Other Notations
1 M
STD BOOK
M 1
STD HOBBY
M M
PROJ EMP
Other Notations
1 1
DEPT CHAIR
1
STD BOOK
PROJ EMP
Roles in Relationships
• Determine the role ETs play in a relationship
• Most of the time is clear from the context, like in STD
and COURSE relationship
Roles in Relationships
• Two situation when they should be expressed
explicitly
• A one to one relationship
• Two ETs having more than one relationship
Roles Examples
ENROLS
STD ENROLMENT ENROLLED
BY
COURSE
HEADS
FACUL-
HEAD
TY
HEADED BY
Roles Examples
STD_TEACH
y
B
Te
ht
ac
ug
he
Ta
s
STD FACULTY
es
Su
vi s
p
er
vi s
r
pe
ed
Su
STD_SUP
yb
Dependencies
• A type of constraint
• Existence dependency
• Identifier dependency
• Referential Dependency
Existence Dependency
bkId
bkId
BOOK
BOOK COPY
bkTitle CopyId
Enhancements in E-R Data Model
EE-R Data Model
• Different proposals
• Most common feature is
representation of supertypes and
subtypes
• A popular feature of Object Oriented
paradigm
Super/Subtypes
• Also called generalization/ specialization
• Supertype is called a General Entity type whereas
subtypes are the specializations
Super/Subtypes
General Entity Types
ST PERSON
Grade NoOfHrs
SALARIED HOURLY
AnalSal HourlyRate
Super/Subtypes
Id
Address Name
PERSON
StId Qual
STD FAC
Simple
Composite
Multi-valued
Derived
• Keys are used for data access
• Keys types are
• Super key
• Candidate key
• Primary key
• Alternate key
• Secondary key
• Relationships are link or association between ETs
• Relationships can be unary, binary, ternary or n-ary
• Relationships are represented using diamonds linked
with participant ETs
Unary, Binary and Ternary
Rships
• Relationships have cardinalities
• Cardinalities can be
• One to one
• One to many
• Many to one
• Many to many
• Minimum and maximum cardinalities are also
specified in the E-R data model
• Different notations are used in E-R data model to
represent cardinalities
• Enhanced E-R data model adds the additional features
in the E-R data model
• Supertype/subtype relationship also called gen/spec
includes inheritance
Max_Dura Descrip
Prog_ID Course_id CTitle
Prog_ID
Crd_Hou
PROGRAM COURSE
Fname Address
Sname Course_id CSemes
Prog_ID
Phone
#StudID Semester
Prog_ID
STUDENT Sem_joinn COURSES
OFFERED
CGPA
Course_Id Shift
Semester
Prog_ID Semester
Stuid_id
Section
#StudID
Prog_ID
EVALUATION Assign
RESULT
Quiz
Attempt
Grade Midterm
Final
Designing Logical DB
• Logical DB design is obtained from
conceptual DB design
• Generally involves transforming E-R
data model to relational data model
• We have studied both DMs, now how
to perform transformation
Transforming Rules
• Straightforward rules exist
• Can be performed manually as well as
automatically
• Evaluate even if you use some tool, since multiple
options exist
Mapping Entity Types
• Each regular entity type is
transformed straightaway into a
relation
• PK of the ET is declared as PK of
relation
• Simple attributes of ET are included
into the relation
Mapping Regular ET
Composite Attributes
• Since tables can contain only atomic values composite
attributes need to be represented as a separate
relation
• Quality becomes a limitation
Composite Attrib Example
Multi-valued Attributes
• An ET with a multi-valued attribute is transformed
into two relations
• One contains the entity type and second the muli-
valued attribute
Multi-valued Attribute
• The PK of the second relation is the
PK of first relation and the attribute
value itself
• Values are accessed through
reference of the PK, that also serves
as FK
MV Attrib Example
Mapping Weak ETs
• Identifier dependency: relation for weak entity type
is created and the PK of the strong ET is used as a
whole or part of the relation against weak ET
Identifier Dependency
Example
Mapping Weak ETs
Referential Dependency: relation against weak ET
has got its own PK, the link is established through
FK, however, FK declared as not null
Ref. Dep. Example
Mapping Relationships
• Relationships are mapped according to their degree
and cardinalities
• Starting from binary relationships
Binary Relationships
• Cardinality: one to many
• The PK of the relation against many side ET contains
the PK of the relation for ET on one side as FK
One to Many Example
EMP PROJ
EMP DEPT
empAddr deptName
BOOK STD
bkAuth sFname
BOOK STD
rtDate sFname
bkAuth
bkId stId
STD HOBBY
hName
stAddr
EMP
eQual
manages
EMP
eQual
manages
ITEM
uCost
has Qty
“H” “C”
“S”
HOURLY SALARIED CONSULTANT
1 , 2 , and 3
st nd rd
Normal Forms
By
Carlos Alvarado
San Jose State University
Overview
• Today we’ll talk about:
• Database Normalization
• Data Anomalies Caused by:
• Update, Insertion, Deletion
• Brief History/Overview
• 1st Normal Form
• 2nd Normal Form
• 3rd Normal Form
• Conclusion
Database Normalization
• The main goal of Database Normalization is to
restructure the logical data model of a database to:
• Eliminate redundancy
• Organize data efficiently
• Reduce the potential for data anomalies.
Data Anomalies
• Data anomalies are inconsistencies in the data stored
in a database as a result of an operation such as
update, insertion, and/or deletion.
• Such inconsistencies may arise when have a particular
record stored in multiple locations and not all of the
copies are updated.
Student# Class#
123 102-8
123 104-9
124 209-0
124 102-8
3rd Normal Form
The Requirements
• The requirements to satisfy the 3rd NF:
• All requirements for 2nd NF must be met.
• Eliminate fields that do not depend on the primary key;
• That is, any field that is dependent not only on the primary key
but also on another field must be moved to another table.
3rd Normal Form
Example
Students table:
Student# AdvID AdvName AdvRoom
123 123A James 555
124 123B Smith 467