1. 2. Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden. Modern Database Management. 4th Edition. Upper Saddle River, New Jersey:Prentice Hall (Pearson Educational, Inc), 2005 A. Silberschatz, H.F. Korth, S. Sudarshan. "Database System Concepts (4th Edition). McGrawHill, 2002.
KRISNA ADIYARTA PASCA SARJANA (MAGISTER KOMPUTER) UNIVERSITAS BUDI LUHUR JAKARTA
Objectives
Definition of terms List five properties of relations State two properties of candidate keys Define first, second, and third normal form Describe problems from merging relations Transform E-R and EER diagrams to relations Create tables with entity and relational integrity constraints Use normalization to convert anomalous tables to well-structured relations
Objectives
Definition of terms Describe the physical database design process Choose storage formats for attributes Select appropriate file organizations Describe three types of file organization Describe indexes and their appropriate use Translate a database model into efficient structures Know when and how to use denormalization
Relation
Definition: A relation is a named, two-dimensional table of data Table consists of rows (records) and columns (attribute or field)
It must have a unique name Every attribute value must be atomic (not multivalued, not composite) Every row must be unique (cant have two rows with exactly the same values for all their fields) Attributes (columns) in tables must have unique names The order of the columns must be irrelevant The order of the rows must be irrelevant
Relations (tables) correspond with entity types and with many-to-many relationship types Rows correspond with entity instances and with many-to-many relationship instances Columns correspond with attributes NOTE: The word relation (in relational database) is NOT the same as the word relationship (in E-R model)
Key Fields
Primary keys are unique identifiers of the relation in question. Examples include employee numbers, social security numbers, etc. This is how we can guarantee that all rows are unique Foreign keys are identifiers that enable a dependent relation (on the many side of a relationship) to refer to its parent relation (on the one side of the relationship)
Keys can be simple (a single field) or composite (more than one field) Keys usually are used as indexes to speed up the response to user queries
Combined, these are a composite primary key (uniquely identifies the order line)individually they are foreign keys (implement M:N relationship between order and product)
Integrity Constraints
Domain Constraints
Allowable
Integrity No primary key attribute may be null. All primary key fields MUST have data
Integrity Constraints
Referential Integrityrule states that any foreign key value (on the relation of the many side) MUST match a primary key value in the relation of the one side. (Or the foreign key can be null) For example: Delete Rules
Restrictdont allow delete of parent side if related rows exist in dependent side Cascadeautomatically delete dependent side rows that correspond with the parent side row to be deleted Set-to-Nullset the foreign key in the dependent side to null if deleting from the parent side not allowed for weak entities
Referential integrity constraints are drawn via arrows from dependent to parent table
Referential integrity constraints are implemented with foreign key to primary key references
Simple attributes: E-R attributes map directly onto the relation Composite attributes: Use only their simple, component attributes Multivalued AttributeBecomes a separate relation with a foreign key taken from the superior entity
Mapping a composite attribute (a) CUSTOMER entity type with composite attribute
(b)
a separate relation with a foreign key taken from the superior entity Primary key composed of:
Partial
Example of mapping a weak entity (cont.) b) Relations resulting from weak entity
NOTE: the domain constraint for the foreign key should NOT allow null value if DEPENDENT is a weak entity Foreign key
key on the one side becomes a foreign key on the many side Many-to-ManyCreate a new relation with the primary keys of the two entities as its primary key One-to-OnePrimary key on the mandatory side becomes a foreign key on the optional side
Foreign key
Again, no null value in the foreign keythis is because of the mandatory minimum cardinality
Foreign key goes in the relation on the optional side, Matching the primary key on the mandatory side
Not Assigned
primary key for the association relation is composed of the primary keys of the two entities (as in M:N relationship)
Identifier
It
Assigned
a) An associative entity
Example of mapping an associative entity with an identifier (cont.) b) Three resulting relations
same relation Many-to-ManyTwo relations: One for the entity type One for an associative relation in which the primary key has two attributes, both taken from the primary key of the entity
relation for each entity and one for the associative entity Associative entity has foreign keys to each entity in the relationship
Mapping a ternary relationship a) PATIENT TREATMENT Ternary relationship with associative entity
Mapping a ternary relationship (cont.) b) Mapping the ternary relationship PATIENT TREATMENT
This is why treatment date and time are included in the composite primary key
Supertype/subtype relationships
Data Normalization
Primarily a tool to validate and improve a logical design so that it satisfies certain constraints that avoid
The process of decomposing relations with anomalies to produce smaller, well-structured relations
Well-Structured Relations
A relation that contains minimal data redundancy and allows users to insert, delete, and update rows without causing data inconsistencies Goal is to avoid anomalies
Insertion Anomalyadding new rows forces user to create duplicate data Deletion Anomalydeleting rows may cause a loss of data that would be needed for other future rows Modification Anomalychanging data in a row forces changes to other rows because of duplication
General rule of thumb: A table should not pertain to more than one entity type
Example
Insertioncant enter a new employee without having the employee take a class Deletionif we remove employee 140, we lose information about the existence of a Tax Acc class Modificationgiving a salary increase to employee 100 forces us to update multiple records
Why do these anomalies exist? Because there are two themes (entity types) in this one relation. This results in data duplication and an unnecessary dependency between the entities
unique identifier. One of the candidate keys will become the primary key
E.g. perhaps there is both credit card number and SS# in a tablein this case both are candidate keys
Each
Normalization
Normalization Relations can fall into one or more categories (or classes) called Normal Forms Normal Form: A class of relations free from a certain set of modification anomalies. Normal forms are given name such as: First normal form (1NF) Second normal form (2NF) Third normal form (3NF) Boyce-Codd normal form (BCNF) Fourth normal form (4NF) Fifth normal form (5NF) These forms are cumulative. A relation in Third normal form is also in 2NF and 1NF.
Steps in normalization
IBM Netscape
Company -> County and County -> Tax Rate thus Company -> Tax Rate
What happens if we remove AT&T ? We loose information about 2 different themes. Split this up into two relations:
Company IBM AT&T County Putnam Bergen
FundID, Manager -> InvestmentType FundID, InvestmentType -> Manager Manager -> InvestmentType
FundID, Manager -> InvestmentType FundID, InvestmentType -> Manager Manager -> InvestmentType
99 99 33 22 11
Common Stock Municipal Bonds Common Stock Growth Stocks Common Stock
Stock Fund Janus Fund Janus Fund Scudder Global Fund Scudder Global Fund Kaufmann Fund
Bond Fund Municipal Bonds Dreyfus Short-Intermediate Municipal Bond Fund Municipal Bonds Dreyfus Short-Intermediate Municipal Bond Fund T. Rowe Price Emerging Markets Bond Fund
De-Normalization
Consider the following relation: CUSTOMER (CustomerID, Name, Address, City, State, Zip) This relation is not in DK/NF because it contains a functional dependency not implied by the key. Zip -> City, State We can normalize this into DK/NF by splitting the CUSTOMER relation into two: CUSTOMER (CustomerID, Name, Address, Zip) CODES (Zip, City, State) We may pay a performance penalty - each customer address lookup requires we look in two relations (tables). In such cases, we may de-normalize the relations to achieve a performance improvement.
All-in-One Example
Many of you asked for a "complete" example that would run through all of the normal forms from beginning to end using the same tables. This is tough to do, but here is an attempt: Example relation: EMPLOYEE ( Name, Project, Task, Office, Phone ) Note: Keys are underlined. Example Data:
Name Project Task Office Floor Phone Bill Bill Bill Bill Sue Sue Sue Ed 100X 100X 200Y 200Y 100X 200Y 300Z 100X T1 T2 T1 T2 T33 T33 T33 T2 400 400 400 400 442 442 442 588 4 4 4 4 4 4 4 5 1400 1400 1400 1400 1442 1442 1442 1588
All-in-One Example
Name is the employee's name Project is the project they are working on. Bill is working on two different projects, Sue is working on 3. Task is the current task being worked on. Bill is now working on Tasks T1 and T2. Note that Tasks are independent of the project. Examples of a task might be faxing a memo or holding a meeting. Office is the office number for the employee. Bill works in office number 400. Floor is the floor on which the office is located. Phone is the phone extension. Note this is associated with the phone in the given office. Question : First Normal Form Assume the key is Name, Project, Task. Is EMPLOYEE in 1NF ?
All-in-One Example
Second Normal Form List all of the functional dependencies for EMPLOYEE. Are all of the non-key attributes dependant on all of the key ? Split into two relations EMPLOYEE_PROJECT_TASK and EMPLOYEE_OFFICE_PHONE. EMPLOYEE_PROJECT_TASK (Name, Project, Name Project Task Task)
Name Bill Bill Bill Bill Sue Sue Sue Ed Project 100X 100X 200Y 200Y 100X 200Y 300Z 100X Task T1 T2 T1 T2 T33 T33 T33 T2 Office 400 400 400 400 442 442 442 588 Floor 4 4 4 4 4 4 4 5 Phone 1400 1400 1400 1400 1442 1442 1442 1588 Bill Sue Ed Bill Bill Bill Bill Sue Sue Sue Ed Name 100X 100X 200Y 200Y 100X 200Y 300Z 100X Office 400 442 588 T1 T2 T1 T2 T33 T33 T33 T2 Floor 4 4 5 Phone 1400 1442 1588
All-in-One Example
Third Normal Form
Assume each office has exactly one phone number. Are there any transitive dependencies ? Where are the modification anomalies in EMPLOYEE_OFFICE_PHONE ? Split EMPLOYEE_OFFICE_PHONE. EMPLOYEE_PROJECT_TASK (Name, Project, Task)
EMPLOYEE_OFFICE (Name, Office, Floor) Name Office Floor Bill 400 4 Sue 442 4 Ed 588 5 EMPLOYEE_PHONE (Office, Phone)
Office 400 442 588 Phone 1400 1442 1588
All-in-One Example
Boyce-Codd Normal Form List all of the functional dependencies for EMPLOYEE_PROJECT_TASK, EMPLOYEE_OFFICE and EMPLOYEE_PHONE. Look at the determinants. Are all determinants candidate keys ?
All-in-One Example
Forth Normal Form Are there any multivalued dependencies ? What are the modification anomalies ? Split EMPLOYEE_PROJECT_TASK. EMPLOYEE_PROJECT (Name, Project )
Name Bill Bill Bill Bill Sue Sue Sue Ed Project 100X 100X 200Y 200Y 100X 200Y 300Z 100X Task T1 T2 T1 T2 T33 T33 T33 T2 Name Bill Bill Sue Sue Sue Ed Name Bill Bill Sue Ed Project 100X 200Y 100X 200Y 300Z 100X Task T1 T2 T33 T2
All-in-One Example
Name Bill Sue Ed Office 400 442 588 Floor 4 4 5
R4 (Office, Phone)
All-in-One Example
At each step of the process, we did the following: 1.Write out the relation 2.(optionally) Write out some example data. 3.Write out all of the functional dependencies 4.Starting with 1NF, go through each normal form and state why the relation is in the given normal form.
All-in-One Example
Another short example Consider the following example of normalization for a CUSTOMER relation. Relation Name CUSTOMER (CustomerID, Name, Street, City, State, Zip, Phone) Example Data
CustomerID C101 C102 Name Bill Smith Mary Green Street 123 First St. 11 Birch St. City New Brunswick Old Bridge State Zip NJ NJ Phone
Functional Dependencies CustomerID -> Name, Street, City, State, Zip, Phone Zip -> City, State
All-in-One Example
Normalization 1NF Meets the definition of a relation. 2NF All non key attributes are dependent on all of the key. 3NF There are no transitive dependencies. BCNF Relation CUSTOMER is not in BCNF because one of the determinants Zip can not act as a key for the entire relation. Solution: Split CUSTOMER into two relations: CUSTOMER (CustomerID, Name, Street, Zip, Phone) ZIPCODES (Zip, City, State) Check both CUSTOMER and ZIPCODE to ensure they are both in 1NF up to BCNF. 4NF There are no multi-valued dependencies in either CUSTOMER or ZIPCODES. As a final step, consider de-normalization.
Merging Relations
View IntegrationCombining entities from multiple ER models into common relations Issues to watch out for when merging entities from different ER models:
Synonymstwo
or more attributes with different names but same meaning Homonymsattributes with same name but different meanings Transitive dependencieseven if relations are in 3NF prior to merging, they may not be after merging Supertype/subtype relationshipsmay be hidden prior to merging
Enterprise Keys
Primary
keys that are unique in the whole database, not just within a single relation Corresponds with the concept of an object ID in object-oriented systems
Enterprise keys
a) Relations with enterprise key
relations
Decisions
zAttribute zPhysical
data types
zFile
zIndexes
expectations
zQuery
technology used
optimization
Data volumes
Designing Fields
Field:
CHARfixed-length character VARCHAR2variable-length character (memo) LONGlarge number NUMBERpositive/negative number INEGERpositive/negative whole number DATEactual date BLOBbinary large object (good for graphics, sound clips, etc.)
Code saves space, but costs an additional lookup to obtain actual value
Default valueassumed value if no explicit value Range controlallowable value limitations (constraints or validation rules) Null value controlallowing or prohibiting empty fields Referential integrityrange control (and null value allowances) for foreign-key to primarykey match-ups
Sarbanes-Oxley Act (SOX) legislates importance of financial data integrity
Substitute an estimate of the missing value (e.g., using a formula) Construct a report listing missing values In programs, ignore missing data unless the value is significant (sensitivity testing) Triggers can be used to perform these operations
Physical Records
Physical Record: A group of fields stored in adjacent memory locations and retrieved together as a unit Page: The amount of data read or written in one I/O operation Blocking Factor: The number of physical records per page
Denormalization
Transforming normalized relations into unnormalized physical record specifications Benefits:
Can improve performance (speed) by reducing number of table lookups (i.e. reduce number of necessary join queries)
Data duplication
Partitioning
Horizontal Partitioning: Distributing the rows of a table into several separate files
Useful for situations where different users need access to different rows Three types: Key Range Partitioning, Hash Partitioning, or Composite Partitioning
Vertical Partitioning: Distributing the columns of a table into several separate relations
Useful for situations where different users need access to different columns The primary key must be repeated in each file
Partitioning (cont.)
Advantages of Partitioning:
Efficiency: Records used together are grouped together Local optimization: Each partition can be optimized for performance Security, recovery Load balancing: Partitions stored on different disks, reduces contention Take advantage of parallel processing capability
Disadvantages of Partitioning:
Inconsistent access speed: Slow retrievals across partitions Complexity: Non-transparent partitioning Extra space or update time: Duplicate data; access from multiple partitions
Data Replication
Purposely storing the same data in multiple locations of the database Improves performance by allowing multiple users to access the same data at the same time with minimum contention Sacrifices data integrity due to data duplication Best for data that is not updated often
Physical File:
A
named portion of secondary memory allocated for the purpose of storing physical records Tablespacenamed set of disk storage elements in which physical files for database tables can be stored Extentcontiguous section of disk space
storage Pointersfield of data that can be used to locate related fields or records
File Organizations
Technique for physically arranging records of a file on secondary storage Factors for selecting file organization:
Fast
data retrieval and throughput Efficient storage space utilization Protection from failure and data loss Minimizing need for reorganization Accommodating growth Security from unauthorized use
Records of the file are stored in sequence by the primary key field values
If sorted
every insert or delete requires resort
If not sorted
Average time to find desired record = n/2 n
Indexa separate table that contains organization of records for quick retrieval Primary keys are automatically indexed Oracle has a CREATE INDEX operation, and MS ACCESS allows indexes to be created for most field types Indexing approaches:
B-tree
B-tree index
Leaves of the tree are all at same level consistent access time
Hash algorithm
Usually uses divisionremainder to determine record position. Records with same position are grouped in lists