You are on page 1of 26

Relation Updates and Triggers

Outline
 Table definition
 Tuple insertion/deletion/update
 Triggers

2
Overview (review)
 Table creation involves two tasks
 defining the schema
• using statements like type definitions in C

 formulating constraints, which define what kinds of tuples are


allowed in the table.
• this can be difficult in practice.

3
Creating a table (review)
 CREATE TABLE STUDENTS(
stu-id INTEGER,
name CHAR(20),
cname CHAR(20),
gpa REAL,
PRIMARY KEY (stu-id))

 Other constraints
 UNIQUE
 FOREIGN KEY

 Insert a new record:

stu-id name cname gpa


000001 Bob - -

4
Null values
 Attribute values in a tuple are sometimes unknown (e.g., gpa not
assigned yet) or inapplicable (e.g., no Chinese name).
 NULL is provided for such situations

 The presence of NULL complicates many issues, for example:


 Special operators needed to check if value IS / IS NOT NULL.
 Is cust-id < 8 true or false when cust-id is equal to NULL?

 SELECT acc-id
FROM DEPOSIT
WHERE cust-id IS NOT NULL

 SELECT acc-id
FROM DEPOSIT
WHERE cust-id < 8
Null values (cont.)
 3-valued logic (true, false and unknown)

Expression Result
cust-id < 8 NULL
cust-id = 8 NULL
cust-id = 8 OR amount > 100 TRUE
cust-id = 8 OR amount < 100 NULL
cust-id = 8 AND amount > 100 NULL
cust-id = 8 AND amount < 100 FALSE
cust-id IS NULL TRUE
cust-id IS NOT NULL FALSE
NOT (cust-id < 8), i.e., NOT NULL NULL
6
Null values (cont.)
 We have a 3-valued logic (true, false and unknown).
 WHERE clause eliminates tuples that don’t evaluate to true (i.e.,
discards tuples with false and NULL values).

SELECT acc-id
FROM DEPOSIT
WHERE cust-id < 8

 NULL values are NOT counted by COUNT in SQL Plus.


 SUM, AVG, MAX, and MIN discard NULL values.
 Two tuples are duplicates if corresponding attributes both contain
NULL.
Checking arbitrary constraints
 We want to make sure that every tuple in STUDENTS has a
positive gpa at all times.

 CREATE TABLE STUDENTS


( …,
PRIMARY KEY(…),
CHECK (gpa > 0))

 As a result, the database will reject an insertion or an update, if the


resulting tuple has a 0 or negative gpa.

 We can write more complex conditions in CHECK (see next).

8
Check – Example 2
 We already have a table CLUB, recording the GPA
of all members in the dancing club.

 We want to create a table


PANEL(stu-id, major)
where each tuple corresponds to a member in the
panel of the club.

 We require that every panel member should have


a GPA at least 1.7.

 We can ensure this with CHECK.

9
Check – Example 2
 We require that every panel member should have
a GPA at least 1.7.

 CREATE TABLE PANEL


(stu-id INTEGER,
major CHAR(20),
PRIMARY KEY (stu-id),
CHECK (stu-id IN
(SELECT stu-id FROM CLUB
WHERE gpa >= 1.7)))

 The database will check the condition whenever


 there is an insertion/update on PANEL

 Note: Oracle does not allow CHECK conditions to use subqueries.

10
Outline
 Table definition
 Tuple insertion/deletion/update
 Triggers

11
Insertion
 To insert a single tuple
INSERT INTO DEPOSIT
VALUES('A1', 1, 20000) use '... ' to
quote a string

 Next see how to insert many tuples using a


single statement.

 For each account owned by customer 2,


we will deposit a bonus of 50 dollars.

 INSERT INTO DEPOSIT


SELECT acc-id, cust-id, 50
FROM DEPOSIT
WHERE cust-id = 2
12
Delete tuples
 Delete tuple ('A1', 1, 20k) from
DEPOSIT

 DELETE FROM DEPOSIT


WHERE acc-id = 'A1' AND cust-id = 1 AND amount = 20000

 Delete all tuples recording deposits by the person with cust-id = 1.

 DELETE FROM DEPOSIT


WHERE cust-id = 1

13
Delete tuples – Example 2
 Delete the tuple corresponding to
the account with the largest balance.

 DELETE FROM ACC


WHERE balance =
(SELECT MAX(balance)
FROM ACC)

14
Update tuples
 Update the balance of account A1
to 15k.
 UPDATE ACC
SET balance = 15000
WHERE acc-id = ‘A1’

 For all the accounts with balance at least 10k, give them an interest
of 5%.
 UPDATE ACC
SET balance = balance * 1.05
WHERE balance > 10000

15
Outline
 Table definition
 Tuple insertion/deletion/update
 Triggers

16
Overview
 We have learned to write the following constraints.
 Primary/candidate key (unique)
 Foreign key
 CHECK

 Next, we will discuss another powerful mechanism for writing


constraints.

 Trigger.
 A trigger can be regarded as a procedure automatically executed by
the database, whenever a certain table is modified.

17
Example 1
 STU (stu-id, name, score);
 CREATE OR REPLACE TRIGGER STU_score_constraint
BEFORE INSERT OR UPDATE ON STU
indicates that the trigger will
FOR EACH ROW inspect the affected row.
BEGIN
IF (:new.score < 0 OR :new.score > 100) THEN
RAISE_APPLICATION_ERROR(-20000, ‘Invalid score’);
END IF;
END;
terminate the insertion
.

 INSERT INTO STU VALUES (1, ‘Tony’, 110);


 The database will report an error and refuse to execute the
statement.
 DROP TRIGGER STU-score-constraint;
18
Example 2
 TRAN (stu-id, c-id, score); FIRST-CLASS (stu-id, name);
 We want to make sure that each student inserted into FIRST-CLASS has
an average score at least 85.

 CREATE OR REPLACE TRIGGER FIRST_CLASS_score


BEFORE INSERT OR UPDATE ON FIRST-CLASS
FOR EACH ROW
DECLARE
Local variable declaration
a INTEGER;
BEGIN
SELECT AVG(score) INTO a FROM TRAN
WHERE stu-id = :new.stu-id;
IF (a < 85) THEN
RAISE_APPLICATION_ERROR(-20000, ‘Too low average’);
END IF;
END;
.
19
Example 3
 STU (stu-id, name, dept-id)
DEPT-CNT (dept-id, stu-cnt);

 After a record is inserted or deleted in STU, we need to count the current


number of students in the affected department(s), and update DEP-CNT
accordingly.

 If a department has no student, then it should not appear in DEPT-CNT.

 See the triggers on the next two slides.

20
 STU (stu-id, name, dept-id); DEPT-CNT (dept-id, stu-cnt);
 CREATE OR REPLACE TRIGGER STU_stat_insert
AFTER INSERT ON STU the trigger will be executed
after a successful insert
FOR EACH ROW
DECLARE
c INTEGER; Count # occurrences of new record’s dept-id
BEGIN in table DEPT-CNT and save it into c
SELECT COUNT(*) into c FROM DEPT-CNT
WHERE dept-id = :new.dept-id;
IF (c = 0) THEN If this dept-id doesn’t exist, add a record
INSERT INTO DEPT-CNT VALUES(:new.dept-id, 1);
ELSE Otherwise, increment the student count
UPDATE DEPT-CNT SET stu-cnt = stu-cnt + 1
WHERE dept-id = :new.dept-id;
END IF;
END;
.

21
A Common Mistake
 STU (stu-id, name, dept-id); DEPT-CNT (dept-id, stu-cnt);
 CREATE OR REPLACE TRIGGER STU_stat_insert
AFTER INSERT ON STU
FOR EACH ROW
DECLARE
c INTEGER;
BEGIN
SELECT COUNT(*) into c FROM STU
WHERE dept-id = :new.dept-id;

ORA-04091: table STU is mutating,


… trigger/function may not see it.

END; Should avoid to do query on the


table which the trigger was defined.
.
22
 STU (stu-id, name, dept-id); DEPT-CNT (dept-id, stu-cnt);
 CREATE OR REPLACE TRIGGER STU_stat_delete
AFTER DELETE ON STU the trigger will be executed
FOR EACH ROW after a successful delete
DECLARE
c INTEGER; Find the current student count in the old
BEGIN record’s dept and save it into c
SELECT stu-cnt into c FROM DEPT-CNT
WHERE dept-id = :old.dept-id;
IF (c = 1) THEN If this is last student, delete the dept-id
DELETE FROM DEPT-CNT
WHERE dept-id = :old.dept-id;
ELSE Otherwise, decrement the student count
UPDATE DEPT-CNT SET stu-cnt = stu-cnt - 1
WHERE dept-id = :old.dept-id;
END IF;
END;
.
23
A Specific Example
 Initially
STU DEPT-CNT
stu-id name dept-id dept-id stu-cnt
1 Bobby COMP COMP 2
2 Sherry COMP PHYS 1
3 Timmy PHYS

INSERT INTO STU VALUES (4, ‘Jerry’, ‘COMP’);


INSERT INTO STU VALUES (5, ‘Tony’, ‘MATH’);

24
A Specific Example
 After insertions
STU DEPT-CNT
stu-id name dept-id dept-id stu-cnt
1 Bobby COMP COMP 3
2 Sherry COMP PHYS 1
3 Timmy PHYS MATH 1
4 Jerry COMP
5 Tony MATH

DELETE FROM STU


WHERE stu-id = 2 OR stu-id = 3

25
A Specific Example
 After deletions
STU DEPT-CNT
stu-id name dept-id dept-id stu-cnt
1 Bobby COMP COMP 2
4 Jerry COMP MATH 1
5 Tony MATH

26

You might also like