CIS 330: Applied Database Systems. ER to Relational Relational Algebra

Similar documents
Why Study the Relational Model? The Relational Model. Relational Database: Definitions. The SQL Query Language. Relational Query Languages

Relational Algebra. [R&G] Chapter 4, Part A CS4320 1

Relational Algebra. Chapter 4, Part A. Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1

Database Management Systems. Chapter 4. Relational Algebra. Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1

Relational algebra. Iztok Savnik, FAMNIT. IDB, Algebra

MIS Database Systems Relational Algebra

The Relational Model (ii)

Database Management System. Relational Algebra and operations

Relational Algebra. Relational Query Languages

Database Applications (15-415)

The Relational Model 2. Week 3

The Relational Model. Chapter 3

Relational Query Languages. Relational Algebra. Preliminaries. Formal Relational Query Languages. Relational Algebra: 5 Basic Operations

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

Relational Algebra. Study Chapter Comp 521 Files and Databases Fall

Relational Query Languages

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

Database Management Systems. Chapter 3 Part 2

Relational Algebra and Calculus. Relational Query Languages. Formal Relational Query Languages. Yanlei Diao UMass Amherst Feb 1, 2007

CAS CS 460/660 Introduction to Database Systems. Relational Algebra 1.1

Introduction to Data Management. Lecture #11 (Relational Algebra)

Relational Algebra 1

Database Applications (15-415)

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

High-Level Database Models (ii)

Introduction to Data Management. Lecture #5 (E-R Relational, Cont.)

High Level Database Models

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

The Entity-Relationship Model. Overview of Database Design

The Entity-Relationship Model

Relational Algebra. Note: Slides are posted on the class website, protected by a password written on the board

v Conceptual Design: ER model v Logical Design: ER to relational model v Querying and manipulating data

Relational Algebra Homework 0 Due Tonight, 5pm! R & G, Chapter 4 Room Swap for Tuesday Discussion Section Homework 1 will be posted Tomorrow

Relational Algebra 1

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

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

CONCEPTUAL DESIGN: ER TO RELATIONAL TO SQL

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

Relational Query Languages. Preliminaries. Formal Relational Query Languages. Example Schema, with table contents. Relational Algebra

Relational Algebra 1. Week 4

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

Today s topics. Null Values. Nulls and Views in SQL. Standard Boolean 2-valued logic 9/5/17. 2-valued logic does not work for nulls

CSCC43H: Introduction to Databases. Lecture 3

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

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

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

Database Systems ( 資料庫系統 )

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

CIS 330: Applied Database Systems

Introduction to Data Management. Lecture #11 (Relational Languages I)

Database Systems. Course Administration. 10/13/2010 Lecture #4

OVERVIEW OF DATABASE DEVELOPMENT

Lecture #8 (Still More Relational Theory...!)

Database Applications (15-415)

CompSci 516: Database Systems

ER to Relational Mapping. ER Model: Overview

Database Systems. Course Administration

CIS 330: Applied Database Systems

The Entity-Relationship Model

Overview of DB & IR. ICS 624 Spring Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa

Database Design & Deployment

Introduction to Database Design

The Entity-Relationship Model

The Entity-Relationship Model. Overview of Database Design. ER Model Basics. (Ramakrishnan&Gehrke, Chapter 2)

Introduction to Database Design

Introduction to Database Design. Dr. Kanda Runapongsa Dept of Computer Engineering Khon Kaen University

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

Relational Query Languages: Relational Algebra. Juliana Freire

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

CIS 330: Web-driven Web Applications. Lecture 2: Introduction to ER Modeling

The Entity-Relationship (ER) Model

The Relational Model

Introduction to Database Design

Conceptual Design. The Entity-Relationship (ER) Model

Introduction to Data Management. Lecture #3 (Conceptual DB Design) Instructor: Chen Li

COMP Instructor: Dimitris Papadias WWW page:

Database Management Systems. Session 2. Instructor: Vinnie Costa

RDBMS (Relational Database Management Systems)

The Entity-Relationship (ER) Model 2

Database Management Systems. Chapter 2 Part 2

CS/INFO 330 Entity-Relationship Modeling. Announcements. Goals of This Lecture. Mirek Riedewald

MIS Database Systems Entity-Relationship Model.

Contents. Database. Information Policy. C03. Entity Relationship Model WKU-IP-C03 Database / Entity Relationship Model

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

SQL: Queries, Programming, Triggers

The Relational Model

Lecture 3 SQL - 2. Today s topic. Recap: Lecture 2. Basic SQL Query. Conceptual Evaluation Strategy 9/3/17. Instructor: Sudeepa Roy

SQL. Chapter 5 FROM WHERE

Relational model continued. Understanding how to use the relational model. Summary of board example: with Copies as weak entity

Database Design. ER Model. Overview. Introduction to Database Design. UVic C SC 370. Database design can be divided in six major steps:

Database Applications (15-415)

RELATIONAL ALGEBRA AND CALCULUS

ER Model Overview. The Entity-Relationship Model. Database Design Process. ER Model Basics

Lecture 3 More SQL. Instructor: Sudeepa Roy. CompSci 516: Database Systems

SQL: The Query Language Part 1. Relational Query Languages

Overview. Introduction to Database Design. ER Model. Database Design

Entity-Relationship Diagrams

The Entity-Relationship Model. Steps in Database Design

SQL: Queries, Constraints, Triggers

Review: Where have we been?

Transcription:

CIS 330: Applied Database Systems ER to Relational Relational Algebra 1

Logical DB Design: ER to Relational Entity sets to tables: ssn name Employees lot CREATE TABLE Employees (ssn CHAR(11), name CHAR(20), lot INTEGER, PRIMARY KEY (ssn)) 2 3

Relationship Sets to Tables In translating a relationship set to a relation, attributes of the relation must include: Keys for each participating entity set (as foreign keys). This set of attributes forms a superkey for the relation. All descriptive attributes. CREATE TABLE Works_In( ssn CHAR(1), did INTEGER, since DATE, PRIMARY KEY (ssn, did), FOREIGN KEY (ssn) REFERENCES Employees, FOREIGN KEY (did) REFERENCES Departments) 3 5

Review: Key Constraints Each dept has at most one manager, according to the key constraint on Manages. name ssn lot Employees since Manages dname did budget Departments Translation to relational model? 1-to-1 1-to Many Many-to-1 Many-to-Many 4 6

Translating ER Diagrams with Key Constraints Map relationship to a table: Note that did is the key now! Separate tables for Employees and Departments. Since each department has a unique manager, we could instead combine Manages and Departments. CREATE TABLE Manages( ssn CHAR(11), did INTEGER, since DATE, PRIMARY KEY (did), FOREIGN KEY (ssn) REFERENCES Employees, FOREIGN KEY (did) REFERENCES Departments) CREATE TABLE Dept_Mgr( did INTEGER, dname CHAR(20), budget REAL, ssn CHAR(11), since DATE, PRIMARY KEY (did), FOREIGN KEY (ssn) REFERENCES Employees) 5 7

Review: Participation Constraints Does every department have a manager? If so, this is a participation constraint: the participation of Departments in Manages is said to be total (vs. partial). Every did value in Departments table must appear in a row of the Manages table (with a non-null ssn value!) ssn name lot since did dname budget Employees Manages Departments Works_In since 6 8

Participation Constraints in SQL We can capture participation constraints involving one entity set in a binary relationship, but little else (without resorting to CHECK constraints). CREATE TABLE Dept_Mgr( did INTEGER, dname CHAR(20), budget REAL, ssn CHAR(11) NOT NULL, since DATE, PRIMARY KEY (did), FOREIGN KEY (ssn) REFERENCES Employees, ON DELETE NO ACTION) 7 9

Review: Weak Entities A weak entity can be identified uniquely only by considering the primary key of another (owner) entity. Owner entity set and weak entity set must participate in a one-to-many relationship set (1 owner, many weak entities). Weak entity set must have total participation in this identifying relationship set. name ssn lot cost pname age Employees Policy Dependents 8 10

Translating Weak Entity Sets Weak entity set and identifying relationship set are translated into a single table. When the owner entity is deleted, all owned weak entities must also be deleted. CREATE TABLE Dep_Policy ( pname CHAR(20), age INTEGER, cost REAL, ssn CHAR(11) NOT NULL, PRIMARY KEY (pname, ssn), FOREIGN KEY (ssn) REFERENCES Employees, ON DELETE CASCADE) 9 11

Review: ISA Hierarchies ssn name lot Employees hourly_wages hours_worked As in C++, or other PLs, attributes are inherited. If we declare A ISA B, every A entity is also considered to be a B entity. Hourly_Emps ISA contractid Contract_Emps Overlap constraints: Can Joe be an Hourly_Emps as well as a Contract_Emps entity? (Allowed/disallowed) Covering constraints: Does every Employees entity also have to be an Hourly_Emps or a Contract_Emps entity? (Yes/no) 10 12

Translating ISA Hierarchies to Relations General approach: 3 relations: Employees, Hourly_Emps and Contract_Emps. Hourly_Emps: Every employee is recorded in Employees. For hourly emps, extra info recorded in Hourly_Emps (hourly_wages, hours_worked, ssn); must delete Hourly_Emps tuple if referenced Employees tuple is deleted). Queries involving all employees easy, those involving just Hourly_Emps require a join to get some attributes. Alternative: Just Hourly_Emps and Contract_Emps. Hourly_Emps: ssn, name, lot, hourly_wages, hours_worked. Each employee must be in one of these two subclasses. 11 13

Review: Binary vs. Ternary Relationships What are the additional constraints in the 2nd diagram? ssn name Employees Bad design lot policyid Covers Policies cost pname age Dependents name ssn lot Employees pname age Dependents Purchaser Better design policyid Policies Beneficiary cost 12 7

Binary vs. Ternary Relationships (Contd.) The key constraints allow us to combine Purchaser with Policies and Beneficiary with Dependents. Participation constraints lead to NOT NULL constraints. What if Policies is a weak entity set? CREATE TABLE Policies ( policyid INTEGER, cost REAL, ssn CHAR(11) NOT NULL, PRIMARY KEY (policyid). FOREIGN KEY (ssn) REFERENCES Employees, ON DELETE CASCADE) CREATE TABLE Dependents ( pname CHAR(20), age INTEGER, policyid INTEGER, PRIMARY KEY (pname, policyid). FOREIGN KEY (policyid) REFERENCES Policies, ON DELETE CASCADE) 13 8

Views A view is just a relation, but we store a definition, rather than a set of tuples. CREATE VIEW YoungActiveStudents (name, grade) AS SELECT S.name, E.grade FROM Students S, Enrolled E WHERE S.sid = E.sid and S.age<21 Views can be dropped using the DROP VIEW command. How to handle DROP TABLE if there s a view on the table? DROP TABLE command has options to let the user specify this. 14 18

Views and Security Views can be used to present necessary information (or a summary), while hiding details in underlying relation(s). Given YoungStudents, but not Students or Enrolled, we can find students s who have are enrolled, but not the cid s of the courses they are enrolled in. 15 22

Relational Model: Summary A tabular representation of data. Simple and intuitive, currently the most widely used. Integrity constraints can be specified by the DBA, based on application semantics. DBMS checks for violations. Two important ICs: primary and foreign keys In addition, we always have domain constraints. Powerful and natural query languages exist. Rules to translate ER to relational model 16 15

Relational Query Languages Query languages: Allow manipulation and retrieval of data from a database. Relational model supports simple, powerful QLs: Strong formal foundation based on logic. Allows for much optimization. Query Languages!= programming languages! QLs not expected to be Turing complete. QLs not intended to be used for complex calculations. QLs support easy, efficient access to large data sets. 17 2

Formal Relational Query Languages Two mathematical Query Languages form the basis for real languages (e.g. SQL), and for implementation: Relational Algebra: More operational, very useful for representing execution plans. Relational Calculus: Lets users describe what they want, rather than how to compute it. (Non-operational, declarative.) 18

Preliminaries A query is applied to relation instances, and the result of a query is also a relation instance. Schemas of input relations for a query are fixed (but query will run regardless of instance!) The schema for the result of a given query is also fixed! Determined by definition of query language constructs. Positional vs. named-field notation: Positional notation easier for formal definitions, named-field notation more readable. Both used in SQL 19 4

Example Instances R1 sid bid day 22 101 10/10/96 58 103 11/12/96 Sailors and Reserves relations for our examples. We ll use positional or named field notation, assume that names of fields in query results are `inherited from names of fields in query input relations. S1 S2 sid sname rating age 22 dustin 7 45.0 31 lubber 8 55.5 58 rusty 10 35.0 sid sname rating age 28 yuppy 9 35.0 31 lubber 8 55.5 44 guppy 5 35.0 58 rusty 10 35.0 20 5

Relational Algebra Basic operations: σ π Selection ( ) Selects a subset of rows from relation. Projection ( ) Deletes unwanted columns from relation. Cross-product ( ) Allows us to combine two relations. Set-difference ( ) Tuples in reln. 1, but not in reln. 2. U Union ( ) Tuples in reln. 1 and in reln. 2. Additional operations: Intersection, join, division, renaming: Not essential, but (very!) useful. Since each operation returns a relation, operations can be composed! (Algebra is closed.) 21 6

Projection sname rating yuppy 9 Deletes attributes that are not in projection list. Schema of result contains exactly the fields in the projection list, with the same names that they had in the (only) input relation. Projection operator has to eliminate duplicates! (Why??) Note: real systems typically don t do duplicate elimination unless the user explicitly asks for it. (Why not?) lubber 8 guppy 5 rusty 10 π ( S2) sname, rating age 35.0 55.5 π age ( S2) 22 7

Selection Selects rows that satisfy selection condition. No duplicates in result! (Why?) Schema of result identical to schema of (only) input relation. Result relation can be the input for another relational algebra operation! (Operator composition.) sid sname rating age 28 yuppy 9 35.0 58 rusty 10 35.0 π σ S rating >8 ( 2) sname rating yuppy 9 rusty 10 σ ( ( S )) sname, rating rating>8 2 23 8

Union, Intersection, Set-Difference All of these operations take two input relations, which must be unioncompatible: Same number of fields. `Corresponding fields have the same sid type. sname rating age 22 What dustin is the 7 schema 45.0 of result? S1 S2 sid sname rating age 22 dustin 7 45.0 31 lubber 8 55.5 58 rusty 10 35.0 44 guppy 5 35.0 28 yuppy 9 35.0 S1 S2 sid sname rating age 31 lubber 8 55.5 58 rusty 10 35.0 S1 S2 24 9

Cross-Product Each row of S1 is paired with each row of R1. Result schema has one field per field of S1 and R1, with field names `inherited if possible. Conflict: Both S1 and R1 have a field called sid. (sid) sname rating age (sid) bid day 22 dustin 7 45.0 22 101 10/10/96 22 dustin 7 45.0 58 103 11/12/96 31 lubber 8 55.5 22 101 10/10/96 31 lubber 8 55.5 58 103 11/12/96 58 rusty 10 35.0 22 101 10/10/96 58 rusty 10 35.0 58 103 11/12/96 Renaming operator: ρ ( C( 1 sid1, 5 sid2), S1 R1) 25 10

Joins Condition Join: R >< c S = σ c ( R S) (sid) sname rating age (sid) bid day 22 dustin 7 45.0 58 103 11/12/96 31 lubber 8 55.5 58 103 11/12/96 S 1 R 1 >< S1. sid < R1. sid Result schema same as that of cross-product. Fewer tuples than cross-product, might be able to compute more efficiently Sometimes called a theta-join. 26 11

Joins Equi-Join: A special case of condition join where the condition c contains only equalities. sid sname rating age bid day 22 dustin 7 45.0 101 10/10/96 58 rusty 10 35.0 103 11/12/96 S1>< R1 sid Result schema similar to cross-product, but only one copy of fields for which equality is specified. Natural Join: Equijoin on all common fields. 27 12

Division Not supported as a primitive operator, but useful for expressing queries like: Find sailors who have reserved all boats. Let A have 2 fields, x and y; B have only field y: A/B = x x, y A y B { } i.e., A/B contains all x tuples (sailors) such that for every y tuple (boat) in B, there is an xy tuple in A. Or: If the set of y values (boats) associated with an x value (sailor) in A contains all y values in B, the x value is in A/B. In general, x and y can be any lists of fields; y is the list of fields in B, and x y is the list of fields of A. 28 13

Examples of Division A/B sno s1 s1 s1 s1 s2 s2 s3 s4 s4 A pno p1 p2 p3 p4 p1 p2 p2 p2 p4 pno p2 B1 sno s1 s2 s3 s4 pno p2 p4 B2 sno s1 s4 pno p1 p2 p4 B3 sno s1 A/B1 A/B2 A/B3 29 14

Expressing A/B Using Basic Operators Idea: For A/B, compute all x values that are not `disqualified by some y value in B. x value is disqualified if by attaching y value from B, we obtain an xy tuple that is not in A. Disqualified x values: A/B: π x (( π x ( A) B) A) π x ( A) all disqualified tuples 30 15

Find names of sailors who ve reserved boat #103 Solution 1: π sname (( σ Re serves ) >< Sailors ) bid =103 Solution 2: ρ ( Temp1, σ Re serves) bid =103 ρ ( Temp2, Temp1>< Sailors) π sname ( Temp2) Solution 3: π sname( σ (Re serves>< Sailors)) bid =103 31 16

Find names of sailors who ve reserved a red boat Information about boat color only available in Boats; so need an extra join: π sname (( σ Boats) >< Re serves>< Sailors) color = ' red ' A more efficient solution: π sname ( π π σ sid (( Boats) >< Re s) >< Sailors) bid color = ' red ' A query optimizer can find this, given the first solution! 32 17

Find sailors who ve reserved a red or a green boat Can identify all red or green boats, then find sailors who ve reserved one of these boats: ρ ( Tempboats, ( σ )) color = ' red ' color = ' green ' Boats π sname ( Tempboats>< Re serves>< Sailors) Can also define Tempboats using union! (How?) What happens if is replaced by in this query? 33 18

Find sailors who ve reserved a red and a green boat Previous approach won t work! Must identify sailors who ve reserved red boats, sailors who ve reserved green boats, then find the intersection (note that sid is a key for Sailors): ρ ( Tempred, π (( σ Boats) >< Re serves)) sid color = ' red ' ρ ( Tempgreen, π (( σ Boats) >< Re serves)) sid color = ' green' π sname (( Tempred Tempgreen) >< Sailors) 34 19

Find the names of sailors who ve reserved all boats Uses division; schemas of the input relations to / must be carefully chosen: ρ ( Tempsids, ( π Re serves) / ( π )) sid, bid bid Boats π sname ( Tempsids>< Sailors) To find sailors who ve reserved all Interlake boats:... / π ( σ ) bid bname= ' Interlake' Boats 35 20

Summary The relational model has rigorously defined query languages that are simple and powerful. Relational algebra is more operational; useful as internal representation for query evaluation plans. Several ways of expressing a given query; a query optimizer should choose the most efficient version. 36