Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Relational Model.

Similar presentations


Presentation on theme: "The Relational Model."— Presentation transcript:

1 The Relational Model

2 Relational Database: Definitions
Relational database: a set of relations Relation: made up of 2 parts: Instance : a table, with rows and columns. #Rows = cardinality, #fields = degree / arity. Schema : specifies name of relation, plus name and type of each column. e.g. Students(sid: string, name: string, login: string, age: integer, gpa: real). Can think of a relation as a set of rows or tuples (i.e., all rows are distinct). 3

3 Example

4 Alternative Terminology for Relational Model

5 Relational Keys Superkey Candidate Key
An attribute, or set of attributes, that uniquely identifies a tuple within a relation. Candidate Key Superkey (K) such that no proper subset is a superkey within the relation. In each tuple of R, values of K uniquely identify that tuple (uniqueness). No proper subset of K has the uniqueness property (irreducibility).

6 Relational Keys Primary Key Alternate Keys Foreign Key
Candidate key selected to identify tuples uniquely within relation. Alternate Keys Candidate keys that are not selected to be primary key. Foreign Key Attribute, or set of attributes, within one relation that matches candidate key of some (possibly same) relation.

7 Example The CAR relation schema:
CAR(State, Reg#, SerialNo, Make, Model, Year) has two keys: Key1 = {State, Reg#} Key2 = {SerialNo} which are also superkeys. {SerialNo, Make} is a superkey but not a key.

8 Null values Null Represents value for an attribute that is currently unknown or not applicable for tuple. Deals with incomplete or exceptional data. Represents the absence of a value and is not the same as zero or spaces, which are values.

9 Integrity Constraints
Entity Integrity In a base relation, no attribute of a primary key can be null. Referential Integrity If foreign key exists in a relation, either foreign key value must match a candidate key value of some tuple in its home relation or foreign key value must be wholly null. General Constraints Additional rules specified by users or database administrators that define or constrain some aspect of the enterprise.

10 General Constraints Semantic Integrity Constraints:
based on application semantics and cannot be expressed by the model per se e.g., “the max. no. of hours per employee for all projects he or she works on is 56 hrs per week” A constraint specification language may have to be used to express these SQL-99 allows triggers and assertions to allow for some of these

11 Update Operations on Relations
Integrity constraints should not be violated by the update operations. INSERT a tuple. DELETE a tuple. MODIFY a tuple Several update operations may have to be grouped together. Updates may propagate to cause other updates automatically. This may be necessary to maintain integrity constraints.

12 Update Operations on Relations
In case of integrity violation, several actions can be taken: Cancel the operation that causes the violation (REJECT option) Perform the operation but inform the user of the violation Trigger additional updates so the violation is corrected (CASCADE option, SET NULL option) Execute a user-specified error-correction routine

13 SQL Language for describing database schema and operations on tables
Data Definition Language (DDL): sublanguage of SQL for describing schema

14 Example Schema Student (Id, Name, DeptId, Addr, Status) Professor (Id, Name, DeptId) Course (CrsCode, CrsName, Descr) Transcript (StudId, CrsCode, Semester, Grade) Teaching (ProfId, CrsCode, Semester) Department (DeptId, Name)

15 Table Declaration CREATE TABLE Student ( Id: INTEGER, Name: CHAR(20),
Address: CHAR(50), Status: CHAR(10) ) Student Id Name Address Status John Cedar St Freshman Mary 22 Main St Sophomore

16 Primary/Candidate Keys
CREATE TABLE Course ( CrsCode:CHAR(6), CrsName: CHAR(20), DeptId: CHAR(4), Descr: CHAR(100), PRIMARY KEY (CrsCode), UNIQUE (DeptId, CrsName) -- candidate key ) Things that start with 2 dashes are comments

17 Default Value Value to be assigned if attribute value in a row
is not specified CREATE TABLE Student ( Id: INTEGER, Name: CHAR(20) NOT NULL, Address: CHAR(50), Status: CHAR(10) DEFAULT ‘freshman’, PRIMARY KEY (Id) )

18 Foreign Key Constraint
CREATE TABLE Teaching ( ProfId: INTEGER, CrsCode: CHAR (6), Semester: CHAR (6), PRIMARY KEY (CrsCode, Semester), FOREIGN KEY (CrsCode) REFERENCES Course, FOREIGN KEY (ProfId) REFERENCES Professor (Id) )

19 Foreign Key Constraint
CrsCode CrsCode ProfId x x y Course Id Teaching y Professor

20 Handling Foreign Key Violations
Insertion into A: Reject if no row exists in B containing foreign key value of the inserted row Deletion from B: NO ACTION: Reject if row(s) in A references row to be deleted (default response) A x B x ? Request to delete row rejected

21 Handling Foreign Key Violations (cont’d)
Deletion from B (cont’d): SET NULL: Set value of foreign key in referencing row(s) in A to null B A null x Row deleted

22 Handling Foreign Key Violations (cont’d)
Deletion from B (cont’d): SET DEFAULT: Set value of foreign key in referencing row(s) in A to default value (y) which must exist in B y B A y x Row deleted

23 Handling Foreign Key Violations (cont’d)
Deletion from B (cont’d): CASCADE: Delete referencing row(s) in A as well A B x x

24 Handling Foreign Key Violations (cont’d)
Update (change) foreign key in A: Reject if no row exists in B containing new foreign key Update candidate key in B (to z) – same actions as with deletion: NO ACTION: Reject if row(s) in A references row to be updated (default response) SET NULL: Set value of foreign key to null SET DEFAULT: Set value of foreign key to default CASCADE: Propagate z to foreign key Cascading when key in B changed from x to z B A z z

25 Specifying Actions CREATE TABLE Teaching ( ProfId INTEGER,
CrsCode CHAR (6), Semester CHAR (6), PRIMARY KEY (CrsCode, Semester), FOREIGN KEY (ProfId) REFERENCES Professor (Id) ON DELETE NO ACTION ON UPDATE CASCADE, FOREIGN KEY (CrsCode) REFERENCES Course (CrsCode) ON DELETE SET NULL ON UPDATE CASCADE )

26 Handling Foreign Key Violations (cont’d)
The action taken to repair the violation of a foreign key constraint in A may cause a violation of a foreign key constraint in C The action specified in C controls how that violation is handled; If the entire chain of violations cannot be resolved, the initial deletion from B is rejected. y y x x C A B

27 Circularity in Foreign Key Constraint
B1 B2 B3 x x y B A y candidate key: A1 foreign key: A3 references B(B1) candidate key: B1 foreign key: B3 references A(A1) Problem 1: Creation of A requires existence of B and vice versa Solution: CREATE TABLE A ( ……) no foreign key CREATE TABLE B ( ……) include foreign key ALTER TABLE A ADD CONSTRAINT cons FOREIGN KEY (A3) REFERENCES B (B1)

28 Circularity in Foreign Key Constraint (cont’d)
Problem 2: Insertion of row in A requires prior existence of row in B and vice versa Solution: use appropriate constraint checking mode: IMMEDIATE checking DEFERRED checking

29 Semantic Constraints in SQL
Primary key and foreign key are examples of structural (syntactic) constraints Semantic constraints Express the logic of the application at hand: e.g., number of registered students  maximum enrollment

30 Attribute-based checks
Used for application dependent conditions Example: limit attribute values Each row in table must satisfy condition CREATE TABLE Transcript ( StudId: INTEGER, CrsCode: CHAR(6), Semester: CHAR(6), Grade: CHAR(1), CHECK (Grade IN (‘A’, ‘B’, ‘C’, ‘D’, ‘F’)), CHECK (StudId > 0 AND StudId < ) )

31 Attribute-based checks (cont’d)
Example: relate values of attributes in different columns CREATE TABLE Employee ( Id: INTEGER, Name: CHAR(20), Salary: INTEGER, MngrSalary: INTEGER, CHECK ( MngrSalary > Salary) )

32 Another Example CREATE TABLE Sells ( bar CHAR(20),
Use a subquery if you need to mention other attributes or relations CREATE TABLE Sells ( bar CHAR(20), beer CHAR(20) CHECK ( beer IN (SELECT name FROM Beers)), price REAL CHECK ( price <= 5.00 ) );

33 CHECK is never equivalent to a foreign key constraint.
Departments Employees Name Toy Complaint Development EmployeeName Department HourlyWage Winslett Toy 10.00 With a FOREIGN KEY constraint, the change in Departments will be reflected in Employees. Name Complaint Development With CHECK, the change in Departments will not be reflected in Employees.

34 Tuple-Based Checks You can also check a combination of attribute values at INSERT/UPDATE time Only Joe’s Bar can sell beer for more than $5: CREATE TABLE Sells ( bar CHAR(20), beer CHAR(20), price REAL, CHECK (bar = ’Joe’’s Bar’ OR price <= 5.00) );

35 Constraints – Problems
Problem 1: Empty table always satisfies all CHECK constraints. If Employee is empty, there are no rows on which to evaluate the CHECK condition. CREATE TABLE Employee ( Id: INTEGER, Name: CHAR(20), Salary: INTEGER, MngrSalary: INTEGER, CHECK ( 0 < (SELECT COUNT (*) FROM Employee)) )

36 Constraints – Problems
Problem 2: Inter-relational constraints should be symmetric Why should constraint be in Employee and not Manager? What if Employee is empty? CREATE TABLE Employee ( Id: INTEGER, Name: CHAR(20), Salary: INTEGER, MngrSalary: INTEGER, CHECK ((SELECT COUNT (*) FROM Manager) < (SELECT COUNT (*) FROM Employee)) )

37 Assertion Element of database schema
Symmetrically specifies an inter-relational constraint Applies to entire database (not just the individual rows of a single table) hence it works even if Employee is empty CREATE ASSERTION DontFireEveryone CHECK (0 < SELECT COUNT (*) FROM Employee)

38 ASSERTIONs. CREATE ASSERTION assertionName CHECK ( condition ); E.g.No bar can charge more than $5 on average for beer. CREATE ASSERTION NoExpensiveBars CHECK ( NOT EXISTS ( SELECT bar FROM Sells GROUP BY bar HAVING 5.00 < AVG(price) )); Bars with an average price above $5

39 There cannot be more bars than drinkers.
Drinkers(name, addr, phone) Bars(name, addr, license) CREATE ASSERTION FewBars CHECK ( (SELECT COUNT (*) FROM Bars) <= (SELECT COUNT (*) FROM DRINKERS) );

40 When are Assertions checked?
In theory, every ASSERTION is checked after every INSERT/ DELETE/ UPDATE.In practice, the DBMS only has to check sometimes: Adding a drinker can’t violate FewBars. Removing a bar can’t violate NoExpensiveBars. Lowering a beer price can’t violate NoExpensiveBars. But is the DBMS smart enough to figure this out?

41 Triggers A more general mechanism for handling events
Not in SQL-92, but is in SQL:1999 Trigger is a schema element (like table, assertion, …) CREATE TRIGGER CrsChange AFTER UPDATE OF CrsCode, Semester ON Transcript WHEN (Grade IS NULL) ROLLBACK

42 Triggers Trigger: procedure that starts automatically if specified changes occur to the DBMS Three parts: Event (activates the trigger) Condition (tests whether the triggers should run) Action (what happens if the trigger runs)

43 TRIGGERs. E.g., an INSERT / DELETE / UPDATE to relation R A trigger is an ECA rule: When Event occurs If Condition holds Then do Action Any SQL Boolean condition Any SQL statements

44 Example If someone inserts an unknown beer into Sells(bar, beer, price), add it to Beers with a NULL manufacturer. CREATE TRIGGER BeerTrig AFTER INSERT ON Sells REFERENCING NEW ROW AS NewTuple FOR EACH ROW WHEN (NewTuple.beer NOT IN (SELECT name FROM Beers)) INSERT INTO Beers(name) VALUES(NewTuple.beer); The event The condition The action

45 Syntax for naming the trigger
CREATE TRIGGER name CREATE OR REPLACE TRIGGER name Useful when there is a trigger with that name and you want to modify the trigger.

46 Syntax for describing the condition
Take one element from each of the three columns: INSERT DELETE UPDATE UPDATE OF attribute BEFORE AFTER INSTEAD OF ON relationName Only if the relation is a view

47 Granularity You can execute a trigger once per modified tuple, or once per triggering statement: Statement-level triggers execute once for each SQL statement that triggers them, regardless of how many tuples are modified. Row level triggers are executed once for each modified tuple. The default Request explicitly by including FOR EACH ROW

48 Your condition & action can refer to the tuples being inserted/deleted/updated
INSERT statements imply a new tuple (for row-level) or new set of tuples (for statement-level). DELETE implies an old tuple (row-level) or table (statement-level). UPDATE implies both. Syntax: REFERENCING [NEW OLD][ROW TABLE] AS name “No raise over 10%.” Pick one Pick one

49 Any boolean-valued Condition is ok in WHEN Condition.
Evaluate the condition on the instance before the event Evaluate the condition on the instance after the event INSERT DELETE UPDATE UPDATE OF attribute BEFORE AFTER INSTEAD OF ON relationName No condition

50 The Action The Action is a sequence of SQL statements (modifications).
Surround them by BEGIN END if there is more than one. But queries make no sense in an action, so we are really limited to modifications.

51 Example Sells(bar, beer, price) NastyBars(bar)
The event = changes to prices CREATE TRIGGER PriceTrig AFTER UPDATE OF price ON Sells REFERENCING OLD ROW AS old NEW ROW AS new FOR EACH ROW WHEN (new.price > old.price ) INSERT INTO NastyBars VALUES(new.bar); Updates let us talk about old and new tuples Condition: a raise in price > $1 We need to consider each price change When the price change is great enough, add the bar to NastyBars

52 Before Trigger Example
CREATE TRIGGER Max_EnrollCheck BEFORE INSERT ON Transcript REFERENCING NEW AS N --row to be added FOR EACH ROW WHEN ((SELECT COUNT (T.StudId) FROM Transcript T WHERE T.CrsCode = N.CrsCode AND T.Semester = N.Semester) >= (SELECT C.MaxEnroll FROM Course C WHERE C.CrsCode = N.CrsCode )) ROLLBACK

53 After Trigger Example CREATE TRIGGER LimitSalaryRaise
AFTER UPDATE OF Salary ON Employee REFERENCING OLD AS O NEW AS N FOR EACH ROW WHEN (N.Salary - O.Salary > 0.05 * O.Salary) UPDATE Employee action SET Salary = 1.05 * O.Salary WHERE Id = O.Id Note: The action itself is a triggering event (but in this case a chain reaction is not possible)

54 Views Schema element Part of external schema
A virtual table constructed from actual tables on the fly Can be accessed in queries like any other table Not materialized, constructed when accessed Similar to a subroutine in ordinary programming

55 Views - Examples Part of external schema suitable for use in Bursar’s office: CREATE VIEW CoursesTaken (StudId, CrsCode, Semester) AS SELECT T.StudId, T.CrsCode, T.Semester FROM Transcript T Part of external schema suitable for student with Id : CREATE VIEW CoursesITook (CrsCode, Semester, Grade) AS SELECT T.CrsCode, T.Semester, T.Grade FROM Transcript T WHERE T.StudId = ‘ ’

56 Controlling Authorization in SQL Using Views
GRANT access ON view TO user_list GRANT SELECT ON CoursesTaken TO joe – Thus views can be used to simulate access control to individual columns of a table

57 Updating Views Question: Since views look like tables to users, can they be updated? Answer: Yes – a view update changes the underlying base table to produce the requested change to the view CREATE VIEW CsReg (StudId, CrsCode, Semester) AS SELECT T.StudId, T. CrsCode, T.Semester FROM Transcript T WHERE T.CrsCode LIKE ‘CS%’ AND T.Semester=‘S2000’

58 Updating Views - Problem 1
INSERT INTO CsReg (StudId, CrsCode, Semester) VALUES (1111, ‘CSE305’, ‘S2000’) Question: What value should be placed in attributes of underlying table that have been projected out (e.g., Grade)? Answer: NULL (assuming null allowed in the missing attribute) or DEFAULT

59 Updating Views - Problem 2
INSERT INTO CsReg (StudId, CrsCode, Semester) VALUES (1111, ‘ECO105’, ‘S2000’) Problem: New tuple not in view Solution: Allow insertion (assuming the WITH CHECK OPTION clause has not been appended to the CREATE VIEW statement)

60 Updating Views - Problem 3
Update to a view might not uniquely specify the change to the base table(s) that results in the desired modification of the view (ambiguity) CREATE VIEW ProfDept (PrName, DeName) AS SELECT P.Name, D.Name FROM Professor P, Department D WHERE P.DeptId = D.DeptId

61 Updating Views - Problem 3 (cont’d)
Tuple <Smith, CS> can be deleted from ProfDept by: Deleting row for Smith from Professor (but this is inappropriate if he is still at the University) Deleting row for CS from Department (not what is intended) Updating row for Smith in Professor by setting DeptId to null (seems like a good idea, but how would the computer know?)

62 Updating Views - Restrictions
Updatable views are restricted to those in which No Cartesian product in FROM clause no aggregates, GROUP BY, HAVING For example, if we allowed: CREATE VIEW AvgSalary (DeptId, Avg_Sal ) AS SELECT E.DeptId, AVG(E.Salary) FROM Employee E GROUP BY E.DeptId then how do we handle: UPDATE AvgSalary SET Avg_Sal = 1.1 * Avg_Sal

63 Example: Updating Views
How can I insert a tuple into a table that doesn’t exist? Employee(ssn, name, department, project, salary) CREATE VIEW Developers AS SELECT name, project FROM Employee WHERE department = “Development” This must be “Development” If we make the following insertion: INSERT INTO Developers VALUES(“Joe”, “Optimizer”) INSERT INTO Employee VALUES(NULL, “Joe”, NULL, “Optimizer”, NULL) It becomes:

64 Allow insertions into Developers
CREATE TRIGGER AllowInsert INSTEAD OF INSERT ON Developers REFERENCING NEW ROW AS new FOR EACH ROW BEGIN INSERT INTO Empolyees(name, department, project) VALUES(new.name, `Development’, new.project); END;

65 Transactions SQL defines transaction model based on COMMIT and ROLLBACK. Transaction is logical unit of work with one or more SQL statements guaranteed to be atomic with respect to recovery. An SQL transaction automatically begins with a transaction-initiating SQL statement (e.g., SELECT, INSERT). Changes made by transaction are not visible to other concurrently executing transactions until transaction completes.

66 Transactions Transaction can complete in one of four ways:
COMMIT ends transaction successfully, making changes permanent. ROLLBACK aborts transaction, backing out any changes made by transaction. For programmatic SQL, successful program termination ends final transaction successfully, even if COMMIT has not been executed. For programmatic SQL, abnormal program end aborts transaction.

67 Transactions New transaction starts with next transaction-initiating statement. SQL transactions cannot be nested. SET TRANSACTION configures transaction: SET TRANSACTION [READ ONLY | READ WRITE] | [ISOLATION LEVEL READ UNCOMMITTED | READ COMMITTED|REPEATABLE READ |SERIALIZABLE ]

68 Immediate and Deferred Integrity Constraints
Do not always want constraints to be checked immediately, but instead at transaction commit. Constraint may be defined as INITIALLY IMMEDIATE or INITIALLY DEFERRED, indicating mode the constraint assumes at start of each transaction. In former case, also possible to specify whether mode can be changed subsequently using qualifier [NOT] DEFERRABLE. Default mode is INITIALLY IMMEDIATE.

69 Immediate and Deferred Integrity Constraints
SET CONSTRAINTS statement used to set mode for specified constraints for current transaction: SET CONSTRAINTS {ALL | constraintName [, ]} {DEFERRED ¦ IMMEDIATE}

70 Modifying the Schema ALTER TABLE Student
ADD COLUMN Gpa INTEGER DEFAULT 0 ADD CONSTRAINT GpaRange CHECK (Gpa >= 0 AND Gpa <= 4) ALTER TABLE Transcript DROP CONSTRAINT Cons constraint names are useful DROP TABLE Employee DROP ASSERTION DontFireEveryone

71 Access Control Databases might contain sensitive information
Access has to be limited: Users have to be identified – authentication Generally done with passwords Each user must be limited to modes of access appropriate to that user - authorization SQL:92 provides tools for specifying an authorization policy but does not support authentication (vendor specific)

72 Controlling Authorization in SQL
GRANT access_list ON table TO user_list access modes: SELECT, INSERT, DELETE, UPDATE, REFERENCES GRANT UPDATE (Grade) ON Transcript TO prof_smith – Only the Grade column can be updated by prof_smith GRANT SELECT ON Transcript TO joe – Individual columns cannot be specified for SELECT access (in the SQL standard) – all columns of Transcript can be read – But SELECT access control to individual columns can be simulated through views (next) User name

73 Modifying Tables – Insert
Inserting a single row into a table Attribute list can be omitted if it is the same as in CREATE TABLE NULL and DEFAULT values can be specified INSERT INTO Transcript(StudId, CrsCode, Semester, Grade) VALUES (12345, ‘CSE305’, ‘S2000’, NULL)

74 Bulk Insertion Insert the rows output by a SELECT
CREATE TABLE DeansList ( StudId INTEGER, Credits INTEGER, CumGpa FLOAT, PRIMARY KEY StudId ) INSERT INTO DeansList (StudId, Credits, CumGpa) SELECT T.StudId, 3 * COUNT (*), AVG(T.Grade) FROM Transcript T GROUP BY T.StudId HAVING AVG (T.Grade) > 3.5 AND COUNT(*) > 30

75 Modifying Tables – Delete
Similar to SELECT except: No project list in DELETE clause No Cartesian product in FROM clause (only 1 table name) Rows satisfying WHERE clause (general form, including subqueries, allowed) are deleted instead of output DELETE FROM Transcript T WHERE T.Grade IS NULL AND T.Semester <> ‘S2000’

76 Modifying Data - Update
UPDATE Employee E SET E.Salary = E.Salary * 1.05 WHERE E.Department = ‘R&D’ Updates rows in a single table All rows satisfying WHERE clause (general form, including subqueries, allowed) are updated


Download ppt "The Relational Model."

Similar presentations


Ads by Google