Translating Entity-Relationship to Relational Tables

Similar documents
Translating Entity-Relationship to Relational Tables

E-R Diagram to Relational Schema. Translating Entity-Relationship to Relational Tables. Representing Weak Entity Sets. Representing Strong Entity Sets

Data Modeling and the Entity-Relationship Model

Data Modeling and the Entity-Relationship Model

V. Database Design CS448/ How to obtain a good relational database schema

An Introduction to Structured Query Language

An Introduction to Structured Query Language

Notes. These slides are based on a slide set provided by Prof. M. Tamer Öszu. CS 640 E-R Model Winter / 23. Notes

Overview of E-R model. The Entity-Relationship (E-R) model. used for database (conceptual schema) design

An Introduction to Structured Query Language

An Introduction to Structured Query Language

Notes. These slides are based on slide sets provided by M. T. Öszu and by R. Ramakrishnan and J. Gehrke. CS 640 Views Winter / 15.

An Introduction to Structured Query Language

CS348: INTRODUCTION TO DATABASE MANAGEMENT (Winter, 2011) FINAL EXAMINATION

Techno India Batanagar Computer Science and Engineering. Model Questions. Subject Name: Database Management System Subject Code: CS 601

E-R Diagram to Relational Schema

Sample Question Paper

Translating an ER Diagram to a Relational Schema

The Relational Model

Data about data is database Select correct option: True False Partially True None of the Above

COMP 3400 Mainframe Administration 1

Data Modeling. Yanlei Diao UMass Amherst. Slides Courtesy of R. Ramakrishnan and J. Gehrke

C Examcollection.Premium.Exam.58q

The Relational Model. Roadmap. Relational Database: Definitions. Why Study the Relational Model? Relational database: a set of relations

Which of the following is the best way to prevent most users from viewing AVG_SALARY data?

The Relational Model. Outline. Why Study the Relational Model? Faloutsos SCS object-relational model

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

The DBMS accepts requests for data from the application program and instructs the operating system to transfer the appropriate data.

Database Systems ( 資料庫系統 )

Relational Databases BORROWED WITH MINOR ADAPTATION FROM PROF. CHRISTOS FALOUTSOS, CMU /615

ACS-3902 Fall Ron McFadyen 3D21 Slides are based on chapter 5 (7 th edition) (chapter 3 in 6 th edition)

Chapter 1 SQL and Data

Database Management System (15ECSC208) UNIT I: Chapter 2: Relational Data Model and Relational Algebra

High-Level Database Models (ii)

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall

The Relational Model Constraints and SQL DDL

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept]

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

Relational Model. Topics. Relational Model. Why Study the Relational Model? Linda Wu (CMPT )

The Relational Model 2. Week 3

Carnegie Mellon Univ. Dept. of Computer Science Database Applications. General Overview - rel. model. Overview - detailed - SQL

Notes. CS 640 Relational Algebra Winter / 16. Notes. CS 640 Relational Algebra Winter / 16. Notes

The Relational Model

Where Are We? Next Few Lectures. Integrity Constraints Motivation. Constraints in E/R Diagrams. Keys in E/R Diagrams

CS403- Database Management Systems Solved Objective Midterm Papers For Preparation of Midterm Exam

LAB 3 Notes. Codd proposed the relational model in 70 Main advantage of Relational Model : Simple representation (relationstables(row,

CS403- Database Management Systems Solved MCQS From Midterm Papers. CS403- Database Management Systems MIDTERM EXAMINATION - Spring 2010

CSE 530A. ER Model to Relational Schema. Washington University Fall 2013

The Relational Model

After completing this unit, you should be able to: Define the terms

After completing this unit, you should be able to: Use inner joins to retrieve data from more than one table

High Level Database Models

Announcements (September 18) SQL: Part II. Solution 1. Incomplete information. Solution 3? Solution 2. Homework #1 due today (11:59pm)

The Relational Model

CS425 Midterm Exam Summer C 2012

Chapter 2. DB2 concepts

II B.Sc(IT) [ BATCH] IV SEMESTER CORE: RELATIONAL DATABASE MANAGEMENT SYSTEM - 412A Multiple Choice Questions.

The Relational Model. Why Study the Relational Model? Relational Database: Definitions

Fundamentals, Design, and Implementation, 9/e Copyright 2004 Database Processing: Fundamentals, Design, and Implementation, 9/e by David M.

The Relational Model. Week 2

The Relational Model. Chapter 3

Introduction to Data Management. Lecture #4 (E-R à Relational Design)

CS275 Intro to Databases

The Relational Model. Relational Data Model Relational Query Language (DDL + DML) Integrity Constraints (IC)

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall

The Relational Model. Chapter 3. Database Management Systems, R. Ramakrishnan and J. Gehrke 1

MIDTERM EXAMINATION Spring 2010 CS403- Database Management Systems (Session - 4) Ref No: Time: 60 min Marks: 38

WHAT IS SQL. Database query language, which can also: Define structure of data Modify data Specify security constraints

SQL: Part II. Announcements (September 18) Incomplete information. CPS 116 Introduction to Database Systems. Homework #1 due today (11:59pm)

DATABASE DEVELOPMENT (H4)

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

SUPERKEY A superkey is a combination of attributes that can be used to uniquely identify a database record. A table might have many superkeys.

From ER to Relational Model. Book Chapter 3 (part 2 )

ER to Relational Model. Professor Jessica Lin

CPS510 Database System Design Primitive SYSTEM STRUCTURE

The Entity-Relationship Model. Overview of Database Design

Structured Query Language (SQL)

ITCS 3160 DATA BASE DESIGN AND IMPLEMENTATION

Course Outline Faculty of Computing and Information Technology

CS352 Lecture: Integrity and Security Constraints revised 9/8/06

The Basic (Flat) Relational Model. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Indexes (continued) Customer table with record numbers. Source: Concepts of Database Management

Sankalchand Patel College of Engineering, Visnagar B.E. Semester III (CE/IT) Database Management System Question Bank / Assignment

DATABASE MANAGEMENT SYSTEM

Database Applications (15-415)

The Entity-Relationship Model

Advance Database Management System

Database Systems. Course Administration

Overview of db design Requirement analysis Data to be stored Applications to be built Operations (most frequent) subject to performance requirement

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

Translation of ER-diagram into Relational Schema. Dr. Sunnie S. Chung CIS430/530

Relational Model History. COSC 416 NoSQL Databases. Relational Model (Review) Relation Example. Relational Model Definitions. Relational Integrity

CMPT 354: Database System I. Lecture 2. Relational Model

Chapter 17: Table & Integrity Contraints. Informatics Practices Class XII. By- Rajesh Kumar Mishra. KV No.1, AFS, Suratgarh

Database Management System 9

SQL Interview Questions


Running Example Tables name location

Introduction to Data Management. Lecture #5 Relational Model (Cont.) & E-Rà Relational Mapping

Introduction to Data Management. Lecture #4 (E-R Relational Translation)

Transcription:

Translating Entity-Relationship to Relational Tables Fall 2017 School of Computer Science University of Waterloo Databases CS348 (University of Waterloo) ER to Relational 1 / 39

Outline 1 ER to Relational Mapping 2 Data Definition in SQL (DDL) 3 Views and View Management 4 Data Security/Control (DCL) (University of Waterloo) ER to Relational 2 / 39

E-R Diagram to Relational Schema Main ideas: Each entity set maps to a new table Each attribute maps to a new table column Each relationship set maps to either new table columns or to a new table (University of Waterloo) ER to Relational 3 / 39

Representing Strong Entity Sets Entity set E with attributes a 1,..., a n translates to table E with attributes a 1,..., a n Entity of type E row in table E Primary key of entity set primary key of table Example: Student Major StudentNum StudentName Student StudentNum StudentName Major (University of Waterloo) ER to Relational 4 / 39

Representing Weak Entity Sets Weak entity set E translates to table E Columns of table E should include Attributes of the weak entity set Attributes of the identifying relationship set Primary key attributes of entity set for dominating entities Primary key of weak entity set primary key of table (University of Waterloo) ER to Relational 5 / 39

Representing Weak Entity Sets (cont.) Example: Balance Account AccNum Log Transaction TransNum Date Amount Account AccNum Balance Transaction TransNum AccNum Date Amount (University of Waterloo) ER to Relational 6 / 39

Representing Relationship Sets If the relationship set is an identifying relationship set for a weak entity set then no action needed If we can deduce the general cardinality constraint (1,1) for a component entity set E then add following columns to table E Attributes of the relationship set Primary key attributes of remaining component entity sets Otherwise: relationship set R table R (University of Waterloo) ER to Relational 7 / 39

Representing Relationship Sets (cont.) Columns of table R should include Attributes of the relationship set Primary key attributes of each component entity set Primary key of table R determined as follows If we can deduce the general cardinality constraint (0,1) for a component entity set E, then take the primary key attributes for E Otherwise, choose primary key attributes of each component entity (University of Waterloo) ER to Relational 8 / 39

Representing Relationship Sets (cont.) Example: Score Address Team HomeTeam Visitor Match Location TeamName LocName Team TeamName Location LocName Address Match HomeTeamName VisitorTeamName LocName Score Note that the role name of a component entity set should be prepended to its primary key attributes, if supplied. (University of Waterloo) ER to Relational 9 / 39

Representing Aggregation Tabular representation of aggregation of R = tabular representation for relationship set R To represent relationship set involving aggregation of R, treat the aggregation like an entity set whose primary key is the primary key of the table for R (University of Waterloo) ER to Relational 10 / 39

Representing Aggregation (cont.) Example: CourseNum Student EnrolledIn Course StudentNum CourseAccount ExpirationDate Account UserId Student StudentNum EnrolledIn StudentNum Course CourseNum CourseNum Account UserId CourseAccount UserId StudentNum CourseNum ExpirationDate (University of Waterloo) ER to Relational 11 / 39

Representing Specialization Create table for higher-level entity set, and treat specialized entity subsets like weak entity sets (without discriminators) Example: Student StudentNumber Student StudentNumber StudentName StudentName Graduate StudentNumber ProfessorName Graduate (1, 1) SupervisedBy (0, N) Professor Degree StudentNumber Degree Professor Degrees ProfessorName ProfessorName (University of Waterloo) ER to Relational 12 / 39

Representing Generalization (Approach #1) Create a table for each lower-level entity set only Columns of new tables should include Attributes of lower level entity set Attributes of the superset The higher-level entity set can be defined as a view on the tables for the lower-level entity sets (University of Waterloo) ER to Relational 13 / 39

Representing Generalization (Approach #1) Example: MakeAndModel LicenceNum Vehicle COVERS Price Tonnage Truck Car MaxSpeed AxelCount PassengerCount Truck LicenceNum MakeAndModel Price Tonnage AxelCount Car LicenceNum MakeAndModel Price MaxSpeed PassengerCount (University of Waterloo) ER to Relational 14 / 39

Representing Generalization (Approach #2) Treat generalization the same as specialization. Example: MakeAndModel LicenceNum Vehicle COVERS Price Vehicle LicenceNum MakeAndModel Price Truck LicenceNum Tonnage AxelCount Tonnage Truck Car MaxSpeed Car LicenceNum MaxSpeed PassengerCount AxelCount PassengerCount (University of Waterloo) ER to Relational 15 / 39

Example Translation: ER Diagram CourseNum Term Course (0, N) SectionOf (1, 1) CourseName SectionNum (1, 1) Section (6, 50) TaughtBy EnrolledIn Mark Professor Off Site Section Student GPA ProfName Location StudentName ProfNum StudentNum (University of Waterloo) ER to Relational 16 / 39

Example Translation: Relational Diagram Course CourseNum CourseName Section CourseNum SectionNum Term ProfNum Off Site Section CourseNum SectionNum Term Location Student StudentNum StudentName GPA EnrolledIn CourseNum SectionNum StudentNum Term Mark Professor ProfNum ProfName (University of Waterloo) ER to Relational 17 / 39

Outline 1 ER to Relational Mapping 2 Data Definition in SQL (DDL) 3 Views and View Management 4 Data Security/Control (DCL) (University of Waterloo) ER to Relational 18 / 39

Defining Relations and Integrity Constraints in SQL connected with a table (definition) Primary Keys Foreign Keys CHECK constraints separate ECA rules (triggers) (University of Waterloo) ER to Relational 19 / 39

Tebles with a Primary Key specifies a attributes of a table (w/types) specifies a primary key in a table syntax: CREATE TABLE <name> (... <attributes>, PRIMARY KEY ( <list of attr> ) ) also creates an unique index on the key (University of Waterloo) ER to Relational 20 / 39

Example create table DEPT ( ID integer not NULL, DeptName char(20), MgrNO char(3), PRIMARY KEY (ID) ) (University of Waterloo) ER to Relational 21 / 39

Example (cont.) sql => insert into DEPT values \ sql (cont.) => ( 1, Computer Science, 000100) DB20000I The SQL command completed successfully. sql => insert into DEPT values \ sql (cont.) => ( 1, Computer Science, 000100) SQL0803N One or more values in the INSERT or UPDATE statement are not valid because they would produce duplicate rows for a table with a unique index. SQLSTATE=23505 (University of Waterloo) ER to Relational 22 / 39

Foreign Key specifies an referential constraint syntax: CREATE TABLE <name> (... <attributes>, FOREIGN KEY ( <attrs> ) REFERENCES <ref-table>( <attrs> ) ON DELETE <delete-action> ON UPDATE <update action> the actions can be: RESTRICT produce an error CASCADE propagate the delete SET NULL set to unknown (University of Waterloo) ER to Relational 23 / 39

Example create table EMP ( SSN integer not NULL, Name char(20), Dept integer, Salary dec(8,2), primary key (SSN), foreign key (Dept) references DEPT(ID) on delete cascade on update restrict) (University of Waterloo) ER to Relational 24 / 39

Example (cont.) db2 => insert into EMP \ sql (cont.) => values ( 999, DAVE, 2, 50000 ) SQL0530N The insert or update value of FOREIGN KEY "DAVID.EMP.SQL970916001756640" is not equal to any value of the primary key of the parent table. SQLSTATE=23503 db2 => insert into EMP \ sql (cont.) => values ( 999, DAVE, 1, 50000 ) DB20000I The SQL command completed successfully. db2 => select * from emp where SSN=999 SSN NAME DEPT SALARY ----------- -------------------- ---- ---------- 999 DAVE 1 50000.00 (University of Waterloo) ER to Relational 25 / 39

Example (cont.) db2 => delete from DEPT where id=1 DB20000I The SQL command completed successfully. db2 => select * from emp where SSN=999 SSN NAME DEPT SALARY ----------- -------------------- ---- ---------- (University of Waterloo) ER to Relational 26 / 39

CHECK constraints allow checking for correct data: syntax: CREATE TABLE <name> (... <attributes>, CHECK <condition> ) condition is a simple search condition no subqueries (in DB2) (University of Waterloo) ER to Relational 27 / 39

Example create table EMP ( SSN integer not NULL, Name char(20), Dept integer, Salary dec(8,2), primary key (SSN), foreign key (Dept) references DEPT(ID) on delete cascade on update restrict, check ( salary > 0 ) ) db2 => insert into emp values (998, DAVE, 1, 0 ) SQL0545N The requested operation is not allowed because a row does not satisfy the check constraint "DAVID.EMP.SQL970916000939620". SQLSTATE=23513 (University of Waterloo) ER to Relational 28 / 39

Outline 1 ER to Relational Mapping 2 Data Definition in SQL (DDL) 3 Views and View Management 4 Data Security/Control (DCL) (University of Waterloo) ER to Relational 29 / 39

Views Definition (View) A view is a relation whose instance is determined by the instances of other relations. A view has many of the same properties as a table. its schema information appears in the database schema access controls can be applied to it other views can be defined in terms of it (University of Waterloo) ER to Relational 30 / 39

Types of Views Virtual: Views are used only for querying; they are not stored in the database Materialized: The query that makes up the view is executed, the view constructed and stored in the database. (University of Waterloo) ER to Relational 31 / 39

SQL DDL: Views General form: CREATE VIEW <name> [AS] ( <query> ) Example create view ManufacturingProjects ( Select projno, projname, firstnme, lastname From project, employee Where respemp = empno and deptno = D21 ) (University of Waterloo) ER to Relational 32 / 39

Accessing a View Query a view as if it were a base relation. SELECT projname FROM manufacturingprojects (University of Waterloo) ER to Relational 33 / 39

Accessing a View Query a view as if it were a base relation. SELECT projname FROM manufacturingprojects What happens when you query a virtual view? At compile time, the view definition is found The query over the view is modified with the query definition The resulting query is optimized and executed (University of Waterloo) ER to Relational 33 / 39

Updating Views Modifications to a view s instance must be propagated back to instances of relations in conceptual schema. (University of Waterloo) ER to Relational 34 / 39

Updating Views Modifications to a view s instance must be propagated back to instances of relations in conceptual schema. Some views cannot be updated unambiguously. (University of Waterloo) ER to Relational 34 / 39

Updating Views Modifications to a view s instance must be propagated back to instances of relations in conceptual schema. Some views cannot be updated unambiguously. Conceptual Schema Persons NAME CITIZENSHIP Ed Canadian Dave Canadian Wes American NationalPastimes CITIZENSHIP PASTIME Canadian Hockey Canadian Curling American Hockey American Baseball External Schema PersonalPastimes NAME PASTIME Ed Hockey Ed Curling Dave Hockey Dave Curling Wes Hockey Wes Baseball (University of Waterloo) ER to Relational 34 / 39

Updating Views Modifications to a view s instance must be propagated back to instances of relations in conceptual schema. Some views cannot be updated unambiguously. Conceptual Schema Persons NAME CITIZENSHIP Ed Canadian Dave Canadian Wes American NationalPastimes CITIZENSHIP PASTIME Canadian Hockey Canadian Curling American Hockey American Baseball 1 What does it mean to insert (Darryl, Hockey)? External Schema PersonalPastimes NAME PASTIME Ed Hockey Ed Curling Dave Hockey Dave Curling Wes Hockey Wes Baseball (University of Waterloo) ER to Relational 34 / 39

Updating Views Modifications to a view s instance must be propagated back to instances of relations in conceptual schema. Some views cannot be updated unambiguously. Conceptual Schema Persons NAME CITIZENSHIP Ed Canadian Dave Canadian Wes American NationalPastimes CITIZENSHIP PASTIME Canadian Hockey Canadian Curling American Hockey American Baseball 1 What does it mean to insert (Darryl, Hockey)? 2 What does it mean to delete (Dave, Curling)? External Schema PersonalPastimes NAME PASTIME Ed Hockey Ed Curling Dave Hockey Dave Curling Wes Hockey Wes Baseball (University of Waterloo) ER to Relational 34 / 39

View Updates in SQL According to SQL-92, a view is updatable only if its definition satisfies a variety of conditions: The query references exactly one table The query only outputs simple attributes (no expressions) There is no grouping/aggregation/distinct There are no nested queries There are no set operations These rules are more restrictive than necessary. (University of Waterloo) ER to Relational 35 / 39

Materialized Views Problem When a base table changes, the materialized view may also change. (University of Waterloo) ER to Relational 36 / 39

Materialized Views Problem When a base table changes, the materialized view may also change. Solution? Periodically reconstruct the materialized view. Incrementally update the materialized view. (University of Waterloo) ER to Relational 36 / 39

Materialized Views Problem When a base table changes, the materialized view may also change. Solution? Periodically reconstruct the materialized view. Incrementally update the materialized view. Example: Data warehouses (University of Waterloo) ER to Relational 36 / 39

Outline 1 ER to Relational Mapping 2 Data Definition in SQL (DDL) 3 Views and View Management 4 Data Security/Control (DCL) (University of Waterloo) ER to Relational 37 / 39

Data Control Language assigns access rights to database objects Syntax: GRANT <what> ON <object> TO <user(s)> REVOKE <what> ON <object> FROM <user(s)> <what> ON <object> can be DATABASE: BINDADD, CONNECT, CREATETAB CREATE_NOT_FENCED, DBADM INDEX: CONTROL PACKAGE: BIND, CONTROL, EXECUTE TABLE/VIEW: ALTER, CONTROL, INDEX, REFERENCES SELECT, INSERT, DELETE, UPDATE <user(s)> is a list of (i) USER <name> (ii) GROUP <name> (iii) PUBLIC (University of Waterloo) ER to Relational 38 / 39

Summary Schema design summary: 1 Create an ER diagram visualization of the design goals 2 Translate ER-to-Relational 3 Determine FD, MVD, JD,... detect anomalies and decompose find keys 4 Determine inter-relational constraints INDs and foreign key constraints 5 Enforce rest of constraints CHECK declarations ECA rules (only as the last resort!) (University of Waterloo) ER to Relational 39 / 39