540 likes | 552 Views
Learn why the relational model is crucial in database management systems, covering key concepts, SQL querying, integrity constraints, and primary keys.
E N D
Database Management SystemsChapter 3 The Relational Model
Why Study the Relational Model? • Most widely used model. • Vendors: IBM, Informix, Microsoft, Oracle, Sybase, etc. • Simple data representation and it can express complex queries. • Recent competitor: object-oriented model • ObjectStore, Versant, Ontos • A synthesis emerging: object-relational model • Informix Universal Server, UniSQL, O2, Oracle, DB2
Relational Database: Definitions • 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 :specifiesname of relation, plus name and domain/type of each column. • E.G. Students(sid: string, name: string, login: string, age: integer, gpa: real). • Can think of a relation as a setof rows or tuples (i.e., all rows are distinct).
Example Instance of Students Relation • Cardinality = 3, degree = 5, all rows distinct • The order of fields does not matter if the fields are named. • A relation is a set of rows, so the order of rows is not important.
Relational Query Languages • A major strength of the relational model: supports simple, powerful querying of data. • Queries can be written intuitively, and the DBMS is responsible for efficient evaluation. • The key: precise semantics for relational queries. • Allows the optimizer to extensively re-order operations, and still ensure that the answer does not change.
The SQL Query Language • Developed by IBM (system R) in the 1970s • Need for a standard since it is used by many vendors • Standards: • SQL-86 • SQL-89 (minor revision) • SQL-92 (major revision) • SQL-99 (major extensions, current standard)
Creating Relations in SQL • 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 TABLEStudents (sid CHAR(20), name CHAR(30), login CHAR(20), age INTEGER, gpa REAL); string type with different length
Creating Relations in SQL • As another example, the Enrolled table holds information about courses that students take. CREATE TABLEEnrolled (sid CHAR(20), cid CHAR(20), grade CHAR(10));
Adding Tuples • We can insert a single tuple into the Students table as follows: INSERT INTOStudents (sid, name, login, age, gpa) VALUES (53666, ‘Jones’, ‘jones@cs’, 18, 3.4);
Deleting Tuples • We can delete all tuples satisfying some condition (e.g., name = Smith): DELETE S FROMStudents S WHERE S.name = ‘Smith’; • Powerful variants of these commands are available; more later!
Updating Tuples • We can modify the column values in an existing row: Old value UPDATE Students S SET S.age = S.age +1, S.gpa = S.gpa -1 WHERE S.sid = 53688; 19 2.2
Updating Tuples • 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
Integrity Constraints (ICs) • 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. • ICs are specified when schema is defined. • ICs are checked when relations are modified. • A legalinstance of a relation is one that satisfies all specified ICs. • 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!
Primary Key Constraints • A set of fields is a candidate keyfor 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. • 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.
Primary and Candidate Keys in SQL • UNIQUE: Candidate keys (you could have many) • PRIMARY KEY: one of candidate keys is chosen as the primary key. CREATE TABLEStudents (sid CHAR(20), name CHAR(30), login CHAR(20), age INTEGER, gpa REAL, UNIQUE (name, age), PRIMARY KEY (sid));
Name a constraint • 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. • CONSTRAINTconstraint-name CREATE TABLEStudents (sid CHAR(20), name CHAR(30), login CHAR(20), age INTEGER, gpa REAL, UNIQUE (name, age), CONSTRAINT StudentsKey PRIMARY KEY (sid));
Primary and Candidate Keys in SQL • “For a given student and course, there is a single grade.” vs. “Students can take only one course, and receive a single grade for that course; further, no two students in a course receive the same grade.” • Used carelessly, an IC can prevent the storage of database instances that arise in practice! CREATE TABLEEnrolled (sid CHAR(20) cid CHAR(20), grade CHAR(2), PRIMARY KEY (sid, cid) ); CREATE TABLEEnrolled (sid CHAR(20) cid CHAR(20), grade CHAR(2), PRIMARY KEY (sid), UNIQUE (cid, grade) );
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’. • E.g. sid is a foreign key referring to Students: • Enrolled(sid: string, cid: string, grade: string) • If all foreign key constraints are enforced, referential integrity is achieved, i.e., no dangling references.
Foreign Keys in SQL • Only students listed in the Students relation should be allowed to enroll for courses. CREATE TABLEEnrolled (sid CHAR(20), cid CHAR(20), grade CHAR(2), PRIMARY KEY (sid, cid), FOREIGN KEY (sid) REFERENCESStudents(sid) ); Enrolled Students
Enforcing Integrity Constraints • 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. • Inserting a tuple with primary key as null. • Updating a tuple with an existing sid. INSERT INTOStudents (sid, name, login, age, gpa) VALUES (53688, ‘Mike’, ‘mike@ee’, 17, 3.4); INSERT INTOStudents (sid, name, login, age, gpa) VALUES (null, ‘Mike’, ‘mike@ee’, 17, 3.4); UPDATEStudents S SET S.sid = 50000WHERE S.sid=53688;
Enforcing Integrity Constraints • Deletion of Enrolled tuples do not violate referential integrity, but insertions could. • Inserting a tuple with an un-exist sid in Students. • Insertion of Students tuples do not violate referential integrity, but deletions could. INSERT INTOEnrolled (sid, cid, grade) VALUES (51111, ‘Hindi101’, ‘B’);
Ways to handle foreign key violations • 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.
Referential Integrity in SQL 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 ); • When a Students row is deleted, all Enrolled rows that refer to it are to be deleted as well. • When a Students sid is modified, the update is to be rejected if an Enrolled row refers to the modified Students row.
The SQL Query Language • 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 : • To find just names and logins: SELECT * FROM Students S WHERE S.age=18; SELECT S.name, S.login FROM Students S WHERE S.age=18;
Querying Multiple Relations SELECT S.name, E.cid FROM Students S, Enrolled E WHERE S.sid=E.sid AND E.grade=‘A’; • What does the following query compute? Given the following instances of Enrolled and Students: we get:
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;
name ssn lot Employees Logical DB Design: ER to Relational • Entity sets to tables: CREATE TABLEEmployees (ssn CHAR(11), name CHAR(20), lot INTEGER, PRIMARY KEY (ssn));
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. • The primary key is decided by the key constraint of the relationship. • All descriptive attributes.
since name dname ssn budget lot did Works_In Employees Departments Binary Relationship • Each dept has at least one employee, and each employee works for at least one department, according to the key constrainton Works_In. Translation to relational model? Many-to-Many
since name dname ssn budget lot did Works_In Employees Departments CREATE TABLE Works_In( ssn CHAR(11), did INTEGER, since DATE, PRIMARY KEY (ssn, did), FOREIGN KEY (ssn) REFERENCESEmployees, FOREIGN KEY (did)REFERENCESDepartments);
since name dname ssn lot Employees Manages Binary Relationship • Each dept has at most one manager, according to the key constrainton Manages. budget did Departments Translation to relational model? 1-to Many
since name dname ssn lot did budget Employees Manages Departments Translating ER Diagrams with Key Constraints • 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. CREATE TABLE Manages( ssn CHAR(11), did INTEGER, since DATE, PRIMARY KEY (did), FOREIGN KEY (ssn)REFERENCESEmployees, FOREIGN KEY (did)REFERENCES Departments);
since name dname ssn lot did budget Employees Manages Departments Translating ER Diagrams with Key Constraints • 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. CREATE TABLE Dept_Mgr( did INTEGER, dname CHAR(20), budget REAL, ssn CHAR(11), since DATE, PRIMARY KEY (did), FOREIGN KEY (ssn) REFERENCES Employees);
Binary Relationship to RM • Many-to-many: The primary key of R includes all the attributes in the primary keys of A and B. • One-to-many: The primary key of R is the same as B (i.e., the entity set on the “many” side). • 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.
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). • The primary key of the table includes all the attributes of the primary keys of the participating entity sets.
since name dname ssn budget lot did Works_In2 Employees Departments Locations address capacity CREATE TABLE Works_In2( 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);
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));
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-nullssn value!) since since name name dname dname ssn did did budget budget lot Departments Employees Manages Works_In since
Participation Constraints in SQL • 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, ssn CHAR(11) NOT NULL, since DATE, PRIMARY KEY (did), FOREIGN KEY (ssn) REFERENCES Employees, ON DELETE NO ACTION); An Employees tuple cannot be deleted while it is pointed to by a Dept_Mgr tuple
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 cost pname age ssn lot Policy Dependents Employees
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);
Review: ISA Hierarchies name ssn lot Employees • 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) • 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. hours_worked hourly_wages ISA contractid Contract_Emps Hourly_Emps
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.
name ssn lot Employees hours_worked hourly_wages ISA contractid CREAT TABLE Employees (ssn CHAR(10) NOT NULL DEFAULT ‘999999999’, name CHAR(20), lot INTEGER, CONSTRAINT EmployeesKey PRIMARY KEY (ssn)); Contract_Emps Hourly_Emps CREATE TABLE Hourly_Emps (ssn CHAR(10) NOT NULL DEFAULT ‘999999999’, hourly_wages REAL, hours_worked INTEGER, CONSTRAINT HourlyEmplsKey PRIMARY KEY (ssn), FOREIGN KEY (ssn) REFERENCES Employees ON DELETE CASCADE);
Translating ISA Hierarchies to Relations • Alternative: Just Hourly_Emps and Contract_Emps. • Hourly_Emps: ssn, name, lot, hourly_wages, hours_worked. • Contract_Emps: ssn, name, lot, contractId. • 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.
name ssn lot Employees Monitors until since started_on dname pid pbudget did budget Sponsors Departments Projects Translating ER Diagram with Aggregation
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 TABLEProjects (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);
name ssn lot Employees Policies policyid cost name ssn lot Employees Beneficiary Policies policyid cost Review: Binary vs. Ternary Relationships pname age Dependents Covers • What are the additional constraints in the 2nd diagram? Bad design pname age Dependents Purchaser Better design
Binary vs. Ternary Relationships (Contd.) CREATE TABLE Policies ( policyid INTEGER, cost REAL, ssn CHAR(11) NOT NULL, PRIMARY KEY (policyid). FOREIGN KEY (ssn) REFERENCES Employees, ON DELETE CASCADE); • 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 Dependents ( pname CHAR(20), age INTEGER, policyid INTEGER, PRIMARY KEY (pname, policyid). FOREIGN KEY (policyid) REFERENCES Policies, ON DELETE CASCADE);
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);