Databases 2012 Christian S. Jensen Computer Science, Aarhus University
Constraints Enforced relationships among data single-attribute keys multi-attribute keys foreign keys attribute constraints row constraints assertions Different scopes of constraints Different policies for enforcement 2
Single-Attribute Key NOT NULL the value cannot be NULL DEFAULT value a default value is specified UNIQUE the value is unique in the table unless it is NULL PRIMARY KEY the value is unique in the table the value is never NULL 3
Example CREATE TABLE People ( name VARCHAR(40) NOT NULL, office VARCHAR(15), userid VARCHAR(15) PRIMARY KEY, `group` CHAR(3) ); 4
Multi-Attribute Key PRIMARY KEY ( a 1, a 2,..., a n ) A top-level element of the CREATE statement CREATE TABLE Exams ( studentid CHAR(8), date DATE, time TIME, vip VARCHAR(15), room VARCHAR(40), PRIMARY KEY (studentid, date) ); 5
Enforcing Key Constraints Checked during insert or update If it is violated then a runtime error occurs INSERT INTO Exams VALUES('2008001', '2011-10-15', '15:30:00', csj','turing-230'); INSERT INTO Exams VALUES('2008001', '2011-10-15', '12:45:00', 'amoeller', 'Ada-017'); 6
Foreign Key Specifies that an attribute must reference an attribute in another table The referenced attribute must be a primary key Also possible for multi-attribute keys Similar to E/R constraints: Course Teaches Professor 7
Example CREATE TABLE Rooms ( room VARCHAR(15) PRIMARY KEY, capacity INT ); CREATE TABLE People ( name VARCHAR(40) NOT NULL, office VARCHAR(15) REFERENCES Rooms(room), userid VARCHAR(15) PRIMARY KEY, `group` CHAR(3) ); 8
Enforcing Foreign Key Constraints Source or target table may change Spurious value due to insert or update in source reject the insert or update Dangling value due to delete or update in target default: reject the delete or update cascade: make the same changes in the source set NULL: change source values to NULL 9
room People (source) Example Tables Rooms (target) Turing-216 4 Ada-333 26 Hopper-017 4 capacity userid name group office csj Christian S. Jensen vip Turing-216 doina Doina Bucur phd NULL bnielsen Kai Birger Nielsen tap Hopper-017 10
Example Modifications DELETE FROM Rooms WHERE room= 'Hopper-017'; UPDATE Rooms SET room = 'Turing-HQ' WHERE room = 'Turing-216'; 11
The Cascade Policy People userid name group office csj Christian S. Jensen vip Turing-HQ doina Doina Bucur phd NULL 12
The Set NULL Policy People userid name group office csj Christian S. Jensen vip NULL doina Doina Bucur phd NULL bnielsen Kai Birger Nielsen tap NULL 13
Specifying Policies CREATE TABLE People ( name VARCHAR(40) NOT NULL, office VARCHAR(15) REFERENCES Rooms(room) ON DELETE SET NULL ON UPDATE CASCADE, userid VARCHAR(15) PRIMARY KEY, `group` CHAR(3) ); 14
Attribute Constraints CHECK ( condition ) after an attribute Allows any SQL Boolean including subqueries CREATE TABLE People ( name VARCHAR(40) NOT NULL, office VARCHAR(15), userid VARCHAR(15) PRIMARY KEY, `group` CHAR(3) CHECK (`group`= 'vip' OR `group`= 'phd' OR `group`= 'tap') ); 15
Enforcing Attribute Constraints Conditions are checked during insert or update of the attribute, but not for other modifications Thus, foreign keys cannot be enforced: CREATE TABLE People ( ); name office userid `group` VARCHAR(40) NOT NULL, VARCHAR(15) CHECK (office IN (SELECT room FROM Rooms)), VARCHAR(15) PRIMARY KEY, CHAR(3) 16
Row Constraints CHECK ( condition ) at top-level Conditions are checked during insert or update of any attribute CREATE TABLE Meetings ( ); meetid date slot owner what INT, DATE, INT, VARCHAR(15), VARCHAR(40), CHECK (slot > 16 OR what NOT LIKE '%beer%') 17
Assertions Global constraints on the entire database CREATE ASSERTION StayOutOfMyOffice CHECK ( (SELECT COUNT(*) FROM People WHERE office= 'Turing-216') <= 1 ); Not in MySQL, DB2 18
Enforcing Assertions Checked after every database modification But a clever system can analyze which changes can possibly affect the assertion For StayOutOfMyOffice, we can ignore modifications of tables other than People deletions from People insertions into People where office Turing-216 updates of People where office is unchanged 19
Triggers Constraints have fixed reactions to violations Triggers enable general reactions Three components event: AFTER, BEFORE for each of INSERT, DELETE, UPDATE condition: any SQL Boolean expression action: any sequence of SQL modifications 20
Triggers as A Sweet Spot Attribute and row checks are efficient, but not really expressive Assertions are expressive, but not really efficient Triggers have the potential to be both and they can do much more just checks The database becomes active 21
Example CREATE TRIGGER ZombieOffice AFTER INSERT ON People REFERENCING NEW ROW AS NewGuy FOR EACH ROW WHEN (NewGuy.office NOT IN (SELECT room FROM Rooms)) INSERT INTO Rooms(room,capacity) VALUES(NewGuy.office,4); 22
AFTER vs. BEFORE CREATE TRIGGER GetOutOfMyOffice BEFORE INSERT ON People REFERENCING NEW ROW AS NewGuy FOR EACH ROW WHEN (NewGuy.office = 'Turing-216') SET NewGuy.office = 'Turing-224'; 23
INSERT, DELETE, Or UPDATE CREATE TRIGGER GetOutOfMyOffice2 BEFORE UPDATE ON People REFERENCING NEW ROW AS NewGuy FOR EACH ROW WHEN (NewGuy.office = 'Turing-216') SET NewGuy.office = 'Turing-224'; 24
Row-Level Or Statement-Level FOR EACH ROW performs the action once for each row FOR EACH STATEMENT performs the action once CREATE TRIGGER LogInsert AFTER INSERT ON People FOR EACH STATEMENT INSERT INTO LogFile VALUES('People', CURRENT_TIME); 25
Referencing Old And New An INSERT implies a new row (FOR EACH ROW) a new table (FOR EACH STATEMENT) A DELETE implies an old row (FOR EACH ROW) an old table (FOR EACH STATEMENT) An UPDATE implies both new and old versions These are refered to as NEW,OLD ROW, TABLE 26
Example CREATE TRIGGER PromotionOfficeDefault AFTER UPDATE ON People REFERENCING OLD ROW AS OldGuy FOR EACH ROW NEW ROW AS NewGuy WHEN (OldGuy.group = 'phd' AND NewGuy.group = 'vip' AND NewGuy.office IS NULL) UPDATE People SET office = 'Turing-224' WHERE userid = NewGuy.userid; 27
Views A view is a virtual table/a named query defined as a function of base tables or other views CREATE VIEW Vips AS SELECT * FROM People WHERE `group` = 'vip'; SELECT * FROM Vips; 28
A Joined View CREATE VIEW BusyDays AS SELECT name, date FROM People, Meetings WHERE People.userid = Meetings.owner; SELECT * FROM BusyDays, Vips WHERE BusyDays.name = Vips.name; 29
Meaning of Views View definitions are pasted in place of uses: SELECT * FROM BusyDays, Vips WHERE BusyDays.name = Vips.name; SELECT * FROM (SELECT name, date FROM People, Meetings WHERE People.userid = Meetings.owner) BusyDays, (SELECT * FROM People WHERE `group` = 'vip') Vips WHERE BusyDays.name = Vips.name; 30
Materialized Views Views may alternatively be stored as tables CREATE MATERIALIZED VIEW VipsM AS SELECT * FROM People WHERE group = 'vip'; This requires recomputation whenever the view may have changed 31
Efficiency Trade-Off A materialized view is faster for queries slower for modifications A typical compromise: recompute the view periodically This only works if correctness is not critical mailing spam to customers computing pie charts from sales statistics 32
Modifying Views Generally, it makes no sense to update a view CREATE VIEW AvgCap AS SELECT AVG(capacity) AS average FROM Rooms; UPDATE AvgCap SET average=117; The function is not reversible... 33
Modifiable Views (1/2) Particularly simple views may be modifed only a single table in FROM only SELECT (enough) simple attributes no subqueries in WHERE INSERT INTO Vips VALUES ('Glynn Winskel', 'Turing-222', 'gwinskel', 'vip'); 34
Modifiable Views (2/2) Defaults or NULL appear for missing attributes 35
INSTEAD-OF Triggers Triggers may be used to catch view modifications The intended action is then performed on the underlying base tables This allows human insight to be used 36
Example CREATE VIEW Vips AS SELECT userid, name, office FROM People WHERE `group` = 'vip'; CREATE TRIGGER VipsInsert INSTEAD OF INSERT ON Vips REFERENCING NEW ROW AS NewVip FOR EACH ROW INSERT INTO People VALUES(NewVip.userid, NewVip.name, 'vip', NewVip.office); INSERT INTO Vips VALUES('gwinskel', 'Glynn Winskel', NULL); 37
Another Example CREATE VIEW BusyDays AS SELECT name, date FROM People, Meetings WHERE People.userid = Meetings.owner; CREATE TRIGGER BusyDaysDelete INSTEAD OF DELETE ON BusyDays REFERENCING OLD ROW AS OldDay FOR EACH ROW DELETE FROM Meetings WHERE date = OldDay.date AND owner IN (SELECT userid FROM People WHERE name = OldDay.name); 38
MySQL Code DELIMITER $$ CREATE TRIGGER ZombieOffice AFTER INSERT ON People FOR EACH ROW BEGIN IF (NEW.office NOT IN (SELECT room FROM Rooms)) THEN INSERT INTO Rooms(room,capacity) VALUES(NEW.office,4); END IF; END$$ DELIMITER ; 39
MySQL Code DELIMITER $$ CREATE TRIGGER GetOutOfMyOffice BEFORE INSERT ON People FOR EACH ROW BEGIN IF (NEW.office = 'Turing-216') THEN SET NEW.office = 'Turing-224'; END IF; END$$ DELIMITER ; 40
MySQL Code DELIMITER $$ CREATE TRIGGER GetOutOfMyOffice2 BEFORE UPDATE ON People FOR EACH ROW BEGIN IF (NEW.office = 'Turing-216') THEN SET NEW.office = 'Turing-224'; END IF; END$$ DELIMITER ; 41
MySQL Code DELIMITER $$ CREATE TRIGGER PromotionOfficeDefault AFTER UPDATE ON People FOR EACH ROW BEGIN IF (OLD.group = 'phd' AND NEW.group = 'vip' AND NEW.office IS NULL) THEN UPDATE People SET office = 'Turing-224 WHERE userid = NEW.userid; END IF; END$$ DELIMITER ; 42
MySQL Code MySQL 5.1 does not support triggers with FOR EACH STATEMENT Materialized views are not supported in MySQL. INSTEAD OF triggers are not supported in MySQL. 43