The Relational Model.

Slides:



Advertisements
Similar presentations
IS698: Database Management Min Song IS NJIT. The Relational Data Model.
Advertisements

1 Constraints, Triggers and Active Databases Chapter 9.
Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
Chapter 7 Notes on Foreign Keys Local and Global Constraints Triggers.
CREATE VIEW SYNTAX CREATE VIEW name [(view_col [, view_col …])] AS [WITH CHECK OPTION];
Constraints and Triggers Foreign Keys Local and Global Constraints Triggers.
Chapter 7 Triggers and Active Databases. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 7-2 Trigger Overview Element of the database schema.
1 The Relational Data Model Chapter 4. 2 Data and Its Structure Data is actually stored as bits, but it is difficult to work with data at this level.
Winter 2002Arthur Keller – CS 1809–1 Schedule Today: Jan. 31 (TH) u Constraints. u Read Sections , Project Part 3 due. Feb. 5 (T) u Triggers,
Chapter 3. 2 Chapter 3 - Objectives Terminology of relational model. Terminology of relational model. How tables are used to represent data. How tables.
1 The Relational Data Model Chapter 4. 2 Data and Its Structure Data is actually stored as bits, but it is difficult to work with data at this level.
CPSC-608 Database Systems Fall 2011 Instructor: Jianer Chen Office: HRBB 315C Phone: Notes #4.
1 Relational Model. 2 Relational Database: Definitions  Relational database: a set of relations  Relation: made up of 2 parts: – Instance : a table,
Chapter 3 The Relational Data Model. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 3-2 Data and Its Structure Data is actually stored.
1 A Closer Look Chapter 2. 2 Underlying Concepts of Databases and Transaction Processing.
Fall 2001Arthur Keller – CS 1809–1 Schedule Today Oct. 23 (T) Constraints. u Read Sections Assignment 4 due. Project Part 3 due Oct. 24 (W). Oct.
1 The Big Picture of Databases We are particularly interested in relational databases Data is stored in tables.
Chapter 4 The Relational Model Pearson Education © 2014.
The Relational Model. Review Why use a DBMS? OS provides RAM and disk.
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Triggers, PL/SQL, embedded SQL, JDBC.
1 CSE 480: Database Systems Lecture 5: Relational Data Model.
Winter 2006Keller, Ullman, Cushing9–1 Constraints Commercial relational systems allow much more “fine-tuning” of constraints than do the modeling languages.
CS411 Database Systems Kazuhiro Minami 06: SQL. Constraints & Triggers Foreign Keys Local and Global Constraints Triggers.
FALL 2004CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
Slide Chapter 5 The Relational Data Model and Relational Database Constraints.
IST 210 Constraints and Triggers. IST Constraints and Triggers Constraint: relationship among data elements DBMS should enforce the constraints.
Fall 2001Database Systems1 Triggers Assertions –Assertions describe rules that should hold for a given database. –An assertion is checked anytime a table.
1 Chapter 7 Triggers and Active Databases. 2 Trigger Overview Element of the database schema General form: ON IF THEN –Event- request to execute database.
1 Chapter 7 Triggers and Active Databases. 2 Trigger Overview Element of the database schema General form: ON IF THEN –Event- request to execute database.
Constraints and Triggers. What’s IC? Integrity Constraints define the valid states of SQL-data by constraining the values in the base tables. –Restrictions.
The Relational Model. 2 Relational Model Terminology u A relation is a table with columns and rows. –Only applies to logical structure of the database,
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
The Relational Model © Pearson Education Limited 1995, 2005 Bayu Adhi Tama, M.T.I.
Chapter 3 The Relational Model. Objectives u Terminology of relational model. u How tables are used to represent data. u Connection between mathematical.
1 Schema for Student Registration System Student Student (Id, Name, Addr, Status) Professor Professor (Id, Name, DeptId) Course Course (DeptId, CrsCode,
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Embedded SQL, JDBC. u Read Sections.
1 Introduction to Database Systems, CS420 SQL Constraints.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
1 CS122A: Introduction to Data Management Lecture #4 (E-R  Relational Translation) Instructor: Chen Li.
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
COP Introduction to Database Structures
Databases We are particularly interested in relational databases
Constraints and Triggers
Foreign Keys Local and Global Constraints Triggers
Relational Algebra and SQL
Introduction to Database Systems, CS420
SQL: Advanced Options, Updates and Views Lecturer: Dr Pavle Mogin
Introduction to Database Systems, CS420
CPSC-608 Database Systems
CPSC-310 Database Systems
CPSC-310 Database Systems
2018, Fall Pusan National University Ki-Joune Li
Trigger Overview Element of the database schema
Chapter 4 The Relational Model Pearson Education © 2009.
The Relational Model Relational Data Model
Chapter 4 The Relational Model Pearson Education © 2009.
Chapter 4 The Relational Model Pearson Education © 2009.
The Relational Model Transparencies
CMSC-461 Database Management Systems
Triggers and Active Databases
Chapter 4 The Relational Model Pearson Education © 2009.
Chapter 4 The Relational Model Pearson Education © 2009.
Chapter 4 The Relational Model Pearson Education © 2009.
CPSC-608 Database Systems
SQL – Constraints & Triggers
CPSC-608 Database Systems
The Relational Data Model
CS 405G: Introduction to Database Systems
-Transactions in SQL -Constraints and Triggers
Presentation transcript:

The Relational Model

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

Example

Alternative Terminology for Relational Model

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).

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.

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.

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.

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.

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

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.

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

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

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)

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

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

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) )

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) )

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

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

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

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

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

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

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 )

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

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)

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

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

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 < 100000000) )

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) )

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 ) );

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.

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) );

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)) )

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)) )

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)

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

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) );

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?

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

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)

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

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

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.

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

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

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

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

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.

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 + 1.00) 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

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

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)

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

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 123456789: CREATE VIEW CoursesITook (CrsCode, Semester, Grade) AS SELECT T.CrsCode, T.Semester, T.Grade FROM Transcript T WHERE T.StudId = ‘123456789’

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

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’

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

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)

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

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?)

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

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:

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;

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.

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.

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 ]

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.

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

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

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)

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

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)

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

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’

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