Database Management Systems Chapter 3 The Relational Model

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

Why Study the Relational Model? v Most widely used model. § Vendors: IBM, Informix, Microsoft, Oracle, Sybase, etc. Simple data representation and it can express complex queries. v Recent competitor: object-oriented model v § § Object. Store, Versant, Ontos A synthesis emerging: object-relational model • Informix Universal Server, Uni. SQL, O 2, Oracle, DB 2 Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 2

Relational Database: Definitions v v Relational database: a set of relations with distinct names. Relation: made up of 2 parts: § § Instance : a table, with rows and columns. #Rows = cardinality, #fields = degree. Schema : specifies name of relation, plus name and domain/type of each column. • E. G. Students(sid: string, name: string, login: string, age: integer, gpa: real). v Can think of a relation as a set of rows or tuples (i. e. , all rows are distinct). Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 3

Example Instance of Students Relation v Cardinality = 3, degree = 5, all rows distinct The order of fields does not matter if the fields are named. v A relation is a set of rows, so the order of rows is not important. v Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 4

Relational Query Languages A major strength of the relational model: supports simple, powerful querying of data. v Queries can be written intuitively, and the DBMS is responsible for efficient evaluation. v § § The key: precise semantics for relational queries. Allows the optimizer to extensively re-order operations, and still ensure that the answer does not change. Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 5

The SQL Query Language Developed by IBM (system R) in the 1970 s v Need for a standard since it is used by many vendors v Standards: v § § SQL-86 SQL-89 (minor revision) SQL-92 (major revision) SQL-99 (major extensions, current standard) Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 6

Creating Relations in SQL v Creates the Students relation. Observe that the type (domain) of each field is specified, and enforced by the DBMS whenever tuples are added or modified. CREATE TABLE Students (sid CHAR(20), name CHAR(30), login CHAR(20), age INTEGER, gpa REAL); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke string type with different length 7

Creating Relations in SQL v As another example, the Enrolled table holds information about courses that students take. CREATE TABLE Enrolled (sid CHAR(20), cid CHAR(20), grade CHAR(10)); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 8

Adding Tuples v We can insert a single tuple into the Students table as follows: INSERT INTO Students (sid, name, login, age, gpa) VALUES (53666, ‘Jones’, ‘jones@cs’, 18, 3. 4); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 9

Deleting Tuples v We can delete all tuples satisfying some condition (e. g. , name = Smith): DELETE S FROM Students S WHERE S. name = ‘Smith’; * Powerful variants of these commands are available; more la Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 10

Updating Tuples v We can modify the column values in an existing row: UPDATE Students Old value S SET S. age = S. age +1, S. gpa = S. gpa -1 WHERE S. sid = 53688; 19 2. 2 Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 11

Updating Tuples v Where clause is applied first and determines which rows to be modified. UPDATE Students S SET S. gpa = S. gpa - 0. 1 WHERE S. gpa >= 3. 3; 3. 3 3. 7 Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 12

Integrity Constraints (ICs) v An IC is a condition specified on a database schema and restricts the data that can be stored in an instance of the database, such as domain constraints. § § v A legal instance of a relation is one that satisfies all specified ICs. § v ICs are specified when schema is defined. ICs are checked when relations are modified. DBMS should not allow illegal instances. If the DBMS checks ICs, stored data is more faithful to real-world meaning. § Avoids data entry errors, too! Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 13

Primary Key Constraints v A set of fields is a candidate key for a relation if : 1. No two distinct tuples can have same values in all key fields, and 2. No subset of the set of fields in a key is a unique identifier for a tuple. § Part 2 false? A superkey (a set of fields containing a key). § If there’s >1 key for a relation, one of the keys is chosen (by DBA) to be the primary key. v v E. g. , sid is a key for Students. (What about name? ) The set {sid, gpa} is a superkey. Every relation is guaranteed to have a key. Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 14

Primary and Candidate Keys in SQL v v UNIQUE: Candidate keys (you could have many) PRIMARY KEY: one of candidate keys is chosen as the primary key. CREATE TABLE Students (sid CHAR(20), name CHAR(30), login CHAR(20), age INTEGER, gpa REAL, UNIQUE (name, age), PRIMARY KEY (sid)); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 15

Name a constraint v We could name a constraint in a table. If the constraint is violated, the constraint name is returned and can be used to identify the error. § CONSTRAINT constraint-name CREATE TABLE Students (sid CHAR(20), name CHAR(30), login CHAR(20), age INTEGER, gpa REAL, UNIQUE (name, age), CONSTRAINT Students. Key PRIMARY KEY (sid)); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 16

Primary and Candidate Keys in SQL v v “For a given student and course, CREATE TABLE Enrolled there is a single grade. ” vs. (sid CHAR(20) “Students can take only one cid CHAR(20), course, and receive a single grade CHAR(2), for that course; further, no two PRIMARY KEY (sid, cid) ); students in a course receive the same grade. ” CREATE TABLE Enrolled Used carelessly, an IC can (sid CHAR(20) prevent the storage of database cid CHAR(20), instances that arise in practice! grade CHAR(2), PRIMARY KEY (sid), UNIQUE (cid, grade) ); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 17

Foreign Keys, Referential Integrity Foreign key : Set of fields in one relation that is used to `refer’ to a tuple in another relation. (Must correspond to primary key of the second relation. ) Like a `logical pointer’. v E. g. sid is a foreign key referring to Students: v § § Enrolled(sid: string, cid: string, grade: string) If all foreign key constraints are enforced, referential integrity is achieved, i. e. , no dangling references. Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 18

Foreign Keys in SQL v Only students listed in the Students relation should be allowed to enroll for courses. CREATE TABLE Enrolled (sid CHAR(20), cid CHAR(20), grade CHAR(2), PRIMARY KEY (sid, cid), FOREIGN KEY (sid) REFERENCES Students(sid) Enrolled ); Students Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 19

Enforcing Integrity Constraints v v ICs are specified when a relation is created and enforced when a relation is modified. Violating the primary key constraint, the transaction will be rejected. § Inserting a tuple with an existing sid. INSERT INTO Students (sid, name, login, age, gpa) VALUES (53688, ‘Mike’, ‘mike@ee’, 17, 3. 4); § Inserting a tuple with primary key as null. INSERT INTO Students (sid, name, login, age, gpa) VALUES (null, ‘Mike’, ‘mike@ee’, 17, 3. 4); § Updating a tuple with an existing sid. UPDATE Students S SET S. sid = 50000 WHERE S. sid=53688; Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 20

Enforcing Integrity Constraints v Deletion of Enrolled tuples do not violate referential integrity, but insertions could. § Inserting a tuple with an un-exist sid in Students. INSERT INTO Enrolled (sid, cid, grade) VALUES (51111, ‘Hindi 101’, ‘B’); v Insertion of Students tuples do not violate referential integrity, but deletions could. Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 21

Ways to handle foreign key violations v v If an Enrolled row with un-existing sid is inserted, it is rejected. If a Students row is deleted/updated, § Option 1: Delete/Update all Enrolled rows that refer to the deleted sid in Students (CASCADE). Both are affected § Option 2: Reject the deletion/updating of the Students row if an Enrolled row refers to it (NO ACTION ). [The default action for SQL]. None is affected. § Option 3: Set the sid of Enrolled to some existing (default) sid value in Students for every involved Enrolled row (SET NULL / SET DEFAULT ). Both are affected. Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 22

Referential Integrity in SQL When a Students row is deleted, all Enrolled rows that refer to it are to be deleted as well. v When a Students sid is modified, the update is to be rejected if an Enrolled row refers to the modified Students row. v CREATE TABLE Enrolled (sid CHAR(20), cid CHAR(20), grade CHAR(2), PRIMARY KEY (sid, cid), FOREIGN KEY (sid) REFERENCES Students (sid) ON DELETE CASCADE ON UPDATE NO ACTION ); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 23

The SQL Query Language v v A relational database query is a question about the data, and the answer consists of a new relation containing the result. To find information about all 18 years old students : SELECT * FROM Students S WHERE S. age=18; v To find just names and logins: SELECT S. name, S. login FROM Students S WHERE S. age=18; Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 24

Querying Multiple Relations v What does the following. SELECT S. name, E. cid query compute? FROM Students S, Enrolled E WHERE S. sid=E. sid AND E. grade=‘A’; Given the following instances of Enrolled and Students: we get: Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 25

Example SELECT S. fname As Student_fname, S. lname As Student_lname, E. call_num As course_call_num FROM Students S, Enrolled E WHERE S. sid = E. sid AND S. points > 100; Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 26

Logical DB Design: ER to Relational v Entity sets to tables: CREATE TABLE ssn name lot Employees Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke Employees (ssn CHAR(11), name CHAR(20), lot INTEGER, PRIMARY KEY (ssn)); 27

Relationship Sets to Tables v 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. • The primary key is decided by the key constraint of the relationship. § All descriptive attributes. Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 28

Binary Relationship since name ssn lot did Works_In Employees v dname Each dept has at least one employee, and each employee works for at least one department, according to the key constraint on Works_In. budget Departments Translation to relational model? Many-to-Many Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 29

since name ssn lot Employees dname did Works_In budget Departments CREATE TABLE Works_In( ssn CHAR(11), did INTEGER, since DATE, PRIMARY KEY (ssn, did), FOREIGN KEY (ssn) REFERENCES Employees, FOREIGN KEY (did) REFERENCES Departments); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 30

Binary Relationship since name ssn v Each dept has at most one manager, according to the key constraint on Manages. dname lot Employees did Manages budget Departments Translation to relational model? 1 -to Many Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 31

Translating ER Diagrams with Key Constraints v Map relationship to a table: § § Since each department has most one manager, there are no two tuples with the same did but differ on the ssn value, did is the key now! Separate tables for Employees and Departments. since name ssn dname lot Employees did Manages budget Departments CREATE TABLE Manages( ssn CHAR(11), did INTEGER, since DATE, PRIMARY KEY (did), FOREIGN KEY (ssn) REFERENCES Employees, FOREIGN KEY (did) REFERENCES Departments); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 32

Translating ER Diagrams with Key Constraints v Since each department has a unique manager, we could instead combine Manages and Departments. § ssn can take null values since several departments have no managers. since name ssn dname lot Employees did Manages budget 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); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 33

Binary Relationship to RM Many-to-many: The primary key of R includes all the attributes in the primary keys of A and B. v One-to-many: The primary key of R is the same as B (i. e. , the entity set on the “many” side). v One-to-one: R has two candidate keys. The first (second) one is the same as A (B). One is primary key and the other is unique. v Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 34

Multiple-way Relationship Multi-way relationship set R: Create a table that includes the candidate keys of the participating entity sets the attributes of R (if any). v The primary key of the table includes all the attributes of the primary keys of the participating entity sets. v Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 35

since name ssn lot Employees address dname did budget Works_In 2 Departments Locations capacity CREATE TABLE Works_In 2( ssn CHAR(11), did INTEGER, address CHAR(20), since DATE, PRIMARY KEY (ssn, did, address), FOREIGN KEY (ssn) REFERENCES Employees, FOREIGN KEY (did) REFERENCES Departments, FOREIGN KEY (address) REFERENCES Locations); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 36

name ssn lot Employees supervisor subordinate Reports_To CREATE TABLE Reports_To( supervisor_ssn CHAR(11), subordinate_ssn CHAR(11), PRIMARY KEY (supervisor_ssn, subordinate_ssn), FOREIGN KEY (supervisor_ssn) REFERENCES Employees (ssn), FOREIGN KEY (subordinate_ssn) REFERENCES Employees(ssn)); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 37

Review: Participation Constraints v 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!) since name ssn did lot Employees dname Manages budget Departments Works_In since Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 38

Participation Constraints in SQL v This approach is good for one-to-many relationships, when entity set with key constraint also has a total participation constraint. (Two tables are combined) CREATE TABLE Dept_Mgr( did INTEGER, dname CHAR(20), budget REAL, An Employees tuple cannot ssn CHAR(11) NOT NULL, be deleted while it is pointed to by a Dept_Mgr tuple since DATE, PRIMARY KEY (did), FOREIGN KEY (ssn) REFERENCES Employees, ON DELETE NO ACTION); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 39

Review: Weak Entities v 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 Employees cost Policy Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke pname age Dependents 40

Translating Weak Entity Sets v 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); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 41

Review: ISA Hierarchies name ssn lot Employees As in C++, or other PLs, hourly_wages attributes are inherited. v If we declare A ISA B, every A entity is also considered to be a B entity. v v v hours_worked ISA Hourly_Emps 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) Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 42

Translating ISA Hierarchies to Relations v 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. Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 43

name ssn lot Employees hourly_wages hours_worked ISA Hourly_Emps contractid Contract_Emps CREAT TABLE Employees (ssn CHAR(10) NOT NULL DEFAULT ‘ 99999’, name CHAR(20), lot INTEGER, CONSTRAINT Employees. Key PRIMARY KEY (ssn)); CREATE TABLE Hourly_Emps (ssn CHAR(10) NOT NULL DEFAULT ‘ 99999’, hourly_wages REAL, hours_worked INTEGER, CONSTRAINT Hourly. Empls. Key PRIMARY KEY (ssn), FOREIGN KEY (ssn) REFERENCES Employees ON DELETE CASCADE); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 44

Translating ISA Hierarchies to Relations v Alternative: Just Hourly_Emps and Contract_Emps. § § Hourly_Emps: ssn, name, lot, hourly_wages, hours_worked. Contract_Emps: ssn, name, lot, contract. Id. Each employee must be in one of these two subclasses. If an employee is both an Hourly_Emps and a Contract_Emps entity, then the same name and lot values are stored in two tables. Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 45

Translating ER Diagram with Aggregation ssn name lot Employees Monitors since started_on pid pbudget Projects until dname did Sponsors Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke budget Departments 46

CREATE TABLE Employees (ssn CHAR(11), name CHAR(20), lot INTEGER, PRIMARY KEY (ssn)); CREATE TABLE Departments (did INTEGER, dname CHAR(20), budget REAL, PRIMARY KEY (did)); CREATE TABLE Projects (pid INTEGER, started_on DATE, pbudget REAL, PRIMARY KEY (pid)); CREATE TABLE Sponsors (did INTEGER, pid INTEGER, since DATE, PRIMARY KEY (did, pid), FOREIGN KEY (did) REFERENCES Departments, FOREIGN KEY (pid) REFERENCES Projects); CREATE TABLE Monitors (ssn CHAR(11), did INTEGER, pid INTEGER, until DATE, PRIMARY KEY (ssn, did, pid), FOREIGN KEY (ssn) REFERENCES Employees, FOREIGN KEY (did) REFERENCES Departments, FOREIGN KEY (pid) REFERENCES Projects); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 47

Review: Binary vs. Ternary Relationships ssn name Employees v What are the additional constraints in the 2 nd diagram? pname lot Policies policyid ssn name Dependents Covers Bad design age cost pname lot age Dependents Employees Purchaser Better design policyid Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke Beneficiary Policies cost 48

Binary vs. Ternary Relationships (Contd. ) v v CREATE TABLE Policies ( The key policyid INTEGER, constraints allow cost REAL, us to combine ssn CHAR(11) NOT NULL, Purchaser with PRIMARY KEY (policyid). Policies and FOREIGN KEY (ssn) REFERENCES Employees, Beneficiary with ON DELETE CASCADE); Dependents. Participation CREATE TABLE Dependents ( constraints lead to pname CHAR(20), NOT NULL v constraints. What if Policies is a weak entity set? age INTEGER, policyid INTEGER, PRIMARY KEY (pname, policyid). FOREIGN KEY (policyid) REFERENCES Policies, ON DELETE CASCADE); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 49

Policies is a weak entity set CREATE TABLE Dependents ( pname CHAR(20), ssn CHAR(11), age INTEGER, policyid INTEGER NOT NULL, PRIMARY KEY (pname, policyid, ssn), FOREIGN KEY (policyid, ssn) REFERENCES Policies, ON DELETE CASCADE); Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 50

Views v A view is just a relation, but we store a definition, rather than a set of tuples. CREATE VIEW Young. Active. Students (name, grade) AS SELECT S. name, E. grade FROM Students S, Enrolled E WHERE S. sid = E. sid and S. age<21; v Views can be dropped using the DROP VIEW command. § How to handle DROP TABLE if there’s a view on the table? • View becomes invalid if its base table is dropped. Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 51

Views and Security v Views can be used to present necessary information (or a summary), while hiding details in underlying relation(s). § Given Young. Students, 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. Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 52

Destroying and Altering Relations v Destroys the relation Students. The schema information and the tuples are deleted. DROP TABLE v Students; The schema of Students is altered by adding a new field; every tuple in the current instance is extended with a null value in the new field. ALTER TABLE Students ADD COLUMN first. Year: Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke integer; 53

Relational Model: Summary v v v 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. § § v v 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 Database Management Systems 3 ed, R. Ramakrishnan and J. Gehrke 54
- Slides: 54