Database Constraints, Keys, and Triggers

1
Constraints
Foreign Keys
Local and Global Constraints
Triggers
Lecture notes by Prof Jeffrey Ullman of Stanford
Revised by Xiannong Meng for use at Bucknell
Background
u
We’ve actually used foreign keys,
constraints, and triggers in our
programming.
u
This set of lectures will discuss the
topics in detail.
2
3
Constraints and Triggers
 
u
A 
constraint
 
 is a relationship among data
elements that the DBMS is required to
enforce.
w
Example
: key constraints.
u
Triggers
 
 are only executed when a
specified condition occurs, e.g., insertion
of a tuple.
w
Easier to implement than complex constraints.
4
Kinds of Constraints
 
u
Keys
.
u
Foreign-key
, or referential-integrity.
u
Value-based
 constraints.
w
Constrain values of a particular attribute.
u
Tuple-based
 constraints.
w
Relationship among components.
u
Assertions
: any SQL boolean expression.
5
Review
: Single-Attribute Keys
u
Place PRIMARY KEY or UNIQUE after the
type in the declaration of the attribute.
u
Example
:
  
CREATE TABLE Sneakers(
   
name
 
CHAR(20) UNIQUE,
   
manf
 
CHAR(20)
  
);
6
Review
: Multiattribute Key
u
The 
store
 and 
sneaker
 together are the key for
Sells:
  
CREATE TABLE Sells (
   
store
 
CHAR(20),
   
sneaker
 
VARCHAR(20),
   
price
 
REAL,
   
PRIMARY KEY (store, sneaker)
  
);
7
Foreign Keys
u
Values appearing in attributes of one
relation must appear together in certain
attributes of another relation.
u
Example
: in 
Sells(store, sneaker, price)
,
we might expect that a sneaker value
also appears in Sneaker.name .
8
Expressing Foreign Keys
u
Use keyword REFERENCES, either:
1.
After an attribute (for one-attribute keys).
2.
As an element of the schema:
 
FOREIGN KEY (<list of attributes>)
  
REFERENCES <relation> (<attributes>)
u
Referenced attributes must be declared
PRIMARY KEY or UNIQUE.
9
Example
: With Attribute
CREATE TABLE Sneakers(
 
name
 
CHAR(20) PRIMARY KEY,
 
manf
 
CHAR(20) );
CREATE TABLE Sells (
 
store
 
 CHAR(20),
 
sneaker CHAR(20)
  
REFERENCES Sneakers(name),
 
price
 
REAL );
10
Example
: As Schema Element
CREATE TABLE Sneakers(
 
name
 
CHAR(20) PRIMARY KEY,
 
manf
 
CHAR(20) );
CREATE TABLE Sells (
 
store
 
    CHAR(20),
 
sneaker
 
CHAR(20),
 
price
 
    REAL,
 
FOREIGN KEY(sneaker) REFERENCES
 
Sneakers(name));
11
Enforcing Foreign-Key Constraints
u
If there is a foreign-key constraint
from relation 
R
  to relation 
S
, two
violations are possible:
1.
An insert or update to 
R
  introduces
values not found in 
S
.
2.
A deletion or update to S causes some
tuples of 
R
  to “dangle.”
12
Actions Taken --- (1)
u
Example
: suppose 
R
 = Sells, 
S
 = Sneakers.
u
An insert or update to 
Sells
 that introduces
a nonexistent sneaker must be rejected.
u
A deletion or update to 
Sneakers 
that
removes a sneaker value found in some
tuples of 
Sells
 can be handled in three ways
(next slides).
13
Actions Taken --- (2)
 
1.
Default
 : Reject the modification.
2.
Cascade
 
: Make the same changes in
Sells.
w
Deleted sneaker
: delete Sells tuple.
w
Updated sneaker
: change value in Sells.
3.
Set NULL
 : Set the sneaker to NULL.
14
Example
: Cascade
 
u
Delete the Nike tuple from Sneakers:
w
Then delete all tuples from Sells that have
sneaker= ’Nike’.
u
Update the Sneaker tuple by changing
‘Nike’ to ’Adidas’ in name (for example),
w
Then change all Sells tuples with sneaker=
’Nike’ to sneaker= ’Adidas’.
15
Example
: Set NULL
 
u
Delete the Nike tuple from Sneakers:
w
Change all tuples of Sells that have
sneaker= ’Nike’ to have sneaker= NULL.
u
Update the Nike tuple by changing
‘Nike’ to ‘Adidas’:
w
Same change as for deletion.
16
Choosing a Policy
u
When we declare a foreign key, we may
choose policies SET NULL or CASCADE
independently for deletions and updates.
u
Follow the foreign-key declaration by:
ON [UPDATE, DELETE][SET NULL CASCADE]
u
Two such clauses may be used.
u
Otherwise, the default (reject) is used.
17
Example
: Setting Policy
CREATE TABLE Sells (
 
store
  
CHAR(20),
 
sneaker
 
CHAR(20),
 
price
  
REAL,
 
FOREIGN KEY(sneaker)
  
REFERENCES Sneakers(name)
  
ON DELETE SET NULL
  
ON UPDATE CASCADE
);
18
Attribute-Based Checks
u
Constraints on the value of a particular
attribute.
u
Add CHECK(<condition>) to the
declaration for the attribute.
u
The condition may use the name of the
attribute, but 
any other relation or
attribute name must be in a subquery
.
19
Example
: Attribute-Based Check
CREATE TABLE Sells (
 
store
  
CHAR(20),
 
sneaker
 
CHAR(20)
  
CHECK ( sneaker IN
  
  (SELECT name FROM Sneakers)),
 
price
 
REAL CHECK (price <= 50.00)
);
/* Subquery is not allowed in sqlite3, one’d have to use some trigger, or
a straight list to perform the same. */
20
Example
: Attribute-Based Check in SQLite
CREATE TABLE Sells (
 
store
  
CHAR(20),
 
sneaker
 
CHAR(20)
  
CHECK ( sneaker IN
  
  (‘Nike’, ‘Adidas’, ‘AirJordan’),
 
price
 
REAL CHECK (price <= 50.00)
);
/* Example of Check() that works in SQLite, using a list. */
21
Timing of Checks
u
Attribute-based checks are performed only
when a value for that attribute is inserted or
updated.
w
Example
: 
CHECK (price <= 50.00)
 checks
every new price and rejects the modification (for
that tuple) if the price is more than $50.
w
Example
: 
CHECK (sneaker IN (SELECT
name FROM Sneakers))
 not checked if a
sneaker is deleted from Sneakers (unlike foreign-
keys).
22
Tuple-Based Checks
u
CHECK (<condition>) may be added as
a relation-schema element.
u
The condition may refer to any attribute
of the relation.
w
But other attributes or relations require a
subquery.
u
Checked on insert or update only.
23
Example
: Tuple-Based Check
u
Only Joe’s Store can sell sneakers for more than
$50:
 
CREATE TABLE Sells (
  
store
  
CHAR(20),
  
sneaker
  
CHAR(20),
  
price
  
REAL,
  
CHECK (store= ’Joe’’s Store’ OR
     
price <= 50.00)
 
);
24
Assertions
u
These are database-schema elements,
like relations or views.
u
Defined by:
  
CREATE ASSERTION <name>
   
CHECK (<condition>);
u
Condition may refer to any relation or
attribute in the database schema.
/*SQL92 supports assertion, but not sqlite3. Trigger can
accomplish the same.*/
25
Example
: Assertion
u
In 
Sells(sneaker, store, price)
, no store may
charge an average of more than $50.
CREATE ASSERTION NoRipoffStors CHECK (
 
NOT EXISTS (
  
SELECT store FROM Sells
  
GROUP BY store
  
HAVING 50.00 < AVG(price)
 
));
26
Example
: Assertion
u
In 
Buyers(name, addr, phone)
 and
Stores(name, addr, owner)
, there cannot be
more stores than buyers.
CREATE ASSERTION FewStore CHECK (
 
(SELECT COUNT(*) FROM Stores) <=
 
(SELECT COUNT(*) FROM Buyers)
);
27
Timing of Assertion Checks
u
In principle, we must check every
assertion after every modification to any
relation of the database.
u
A clever system can observe that only
certain changes could cause a given
assertion to be violated.
w
Example
: No change to Sneakers can affect
FewStore.  Neither can an insertion to Buyers.
28
Triggers: Motivation
u
Assertions are powerful, but the DBMS
often can’t tell when they need to be
checked.
u
Attribute- and tuple-based checks are
checked at known times, but are not
powerful.
u
Triggers let the user decide when to
check for any condition.
29
Event-Condition-Action Rules
u
Another name for “trigger” is 
ECA rule
,
or 
event-condition-action
  rule.
u
Event
 
:  typically a type of database
modification, e.g., “insert on Sells.”
u
Condition
 : Any SQL boolean-valued
expression.
u
Action
 : Any SQL statements.
30
Preliminary 
Example
: A Trigger
u
Instead of using a foreign-key
constraint and rejecting insertions into
Sells(store, sneaker, price)
 with
unknown sneakers, a trigger can add
that sneaker to Sneakers, with a NULL
manufacturer.
31
Example
: Trigger Definition
CREATE TRIGGER SneakerTrig
 
AFTER INSERT ON Sells
 
FOR EACH ROW
 
WHEN (New.sneaker NOT IN
  
(SELECT name FROM Sneakers))
   BEGIN
 
INSERT INTO Sneakers(name)
  
VALUES(New.sneaker)
    END;   
/*
new
 and 
old
 references what they are*/
32
Options
: CREATE TRIGGER
u
CREATE TRIGGER <name>
u
Or:
CREATE OR REPLACE TRIGGER <name>
w
Useful if there is a trigger with that name
and you want to modify the trigger.
33
Options
: The Event
 
u
AFTER can be BEFORE.
w
Also, INSTEAD OF, if the relation is a view.
A clever way to execute view modifications:
have triggers translate them to appropriate
modifications on the base tables.
u
INSERT can be DELETE or UPDATE.
w
And UPDATE can be UPDATE . . . ON a
particular attribute.
34
Options
: FOR EACH ROW
 
u
Triggers are either “row-level” or
“statement-level.”
u
FOR EACH ROW indicates row-level; its
absence indicates statement-level.
u
Row level triggers
 : execute once for
each modified tuple.
u
Statement-level triggers
 : execute once
for a SQL statement, regardless of how
many tuples are modified.
 
SQLite doesn’t support “statement-level”
35
Options
: REFERENCING
u
INSERT statements imply a new tuple
(for row-level) or new table (for
statement-level).
w
The “table” is the set of inserted tuples.
u
DELETE implies an old tuple or table.
u
UPDATE implies both.
u
Refer to these by
[NEW OLD][TUPLE TABLE] AS <name>
SQLite doesn’t support “referencing”
36
Options
: The Condition
u
Any boolean-valued condition.
u
Evaluated on the database as it would
exist before or after the triggering
event, depending on whether BEFORE
or AFTER is used.
w
But always before the changes take effect.
u
Access the new/old tuple/table through
the names in the REFERENCING clause.
37
Options
: The Action
u
There can be more than one SQL
statement in the action.
w
Surround by BEGIN . . . END if there is
more than one.
u
But queries make no sense in an action,
so we are really limited to
modifications.
38
Another 
Example
u
Using 
Sells(store, sneaker, price)
 and a
unary relation 
RipoffStores(store)
,
maintain a list of stores that raise the
price of any sneaker by more than $10.
39
The Trigger
CREATE TRIGGER PriceTrig
 
AFTER UPDATE OF price ON Sells
 
FOR EACH ROW
 
WHEN(New.price > Old.price + 10.00)
   BEGIN
 
INSERT INTO RipoffStores
  
VALUES(New.store);
40
Example
: Assertion replaced by Trigger
u
In 
Sells(sneaker, store, price)
, no store may charge an
average of more than $50. We used a Assertion earlier in
SQL92. In SQLite, we can use a Trigger to do the same.
CREATE Trigger NoRipoffStores BEFORE INSERT on Sells
BEGIN
      SELECT
      CASE
      WHEN EXISTS(
           SELECT store FROM Sells
           GROUP BY store
           HAVING 50.00 < AVG(price)
      ) THEN
      RAISE ( abort, 'Invalid price...')
      END; -- select
END; -- begin
Slide Note
Embed
Share

Explore the concepts of constraints, foreign keys, local and global constraints, and triggers in the context of database management systems. Delve into topics such as types of constraints, keys, and expressing foreign keys with examples. Enhance your understanding of database integrity and data relationships.

  • Database Constraints
  • Keys
  • Triggers
  • SQL Operations

Uploaded on Oct 08, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Constraints Foreign Keys Local and Global Constraints Triggers Lecture notes by Prof Jeffrey Ullman of Stanford Revised by Xiannong Meng for use at Bucknell 1

  2. Background We ve actually used foreign keys, constraints, and triggers in our programming. This set of lectures will discuss the topics in detail. 2

  3. Constraints and Triggers A constraint is a relationship among data elements that the DBMS is required to enforce. Example: key constraints. Triggers are only executed when a specified condition occurs, e.g., insertion of a tuple. Easier to implement than complex constraints. 3

  4. Kinds of Constraints Keys. Foreign-key, or referential-integrity. Value-based constraints. Constrain values of a particular attribute. Tuple-based constraints. Relationship among components. Assertions: any SQL boolean expression. 4

  5. Review: Single-Attribute Keys Place PRIMARY KEY or UNIQUE after the type in the declaration of the attribute. Example: CREATE TABLE Sneakers( name CHAR(20) UNIQUE, manf CHAR(20) ); 5

  6. Review: Multiattribute Key The store and sneaker together are the key for Sells: CREATE TABLE Sells ( store CHAR(20), sneaker VARCHAR(20), price REAL, PRIMARY KEY (store, sneaker) ); 6

  7. Foreign Keys Values appearing in attributes of one relation must appear together in certain attributes of another relation. Example: in Sells(store, sneaker, price), we might expect that a sneaker value also appears in Sneaker.name . 7

  8. Expressing Foreign Keys Use keyword REFERENCES, either: 1. After an attribute (for one-attribute keys). 2. As an element of the schema: FOREIGN KEY (<list of attributes>) REFERENCES <relation> (<attributes>) Referenced attributes must be declared PRIMARY KEY or UNIQUE. 8

  9. Example: With Attribute CREATE TABLE Sneakers( name CHAR(20) PRIMARY KEY, manf CHAR(20) ); CREATE TABLE Sells ( store CHAR(20), sneaker CHAR(20) REFERENCES Sneakers(name), price REAL ); 9

  10. Example: As Schema Element CREATE TABLE Sneakers( name CHAR(20) PRIMARY KEY, manf CHAR(20) ); CREATE TABLE Sells ( store CHAR(20), sneaker CHAR(20), price REAL, FOREIGN KEY(sneaker) REFERENCES Sneakers(name)); 10

  11. Enforcing Foreign-Key Constraints If there is a foreign-key constraint from relation R to relation S, two violations are possible: 1. An insert or update to R introduces values not found in S. 2. A deletion or update to S causes some tuples of R to dangle. 11

  12. Actions Taken --- (1) Example: suppose R = Sells, S = Sneakers. An insert or update to Sells that introduces a nonexistent sneaker must be rejected. A deletion or update to Sneakers that removes a sneaker value found in some tuples of Sells can be handled in three ways (next slides). 12

  13. Actions Taken --- (2) 1. Default : Reject the modification. 2. Cascade : Make the same changes in Sells. Deleted sneaker: delete Sells tuple. Updated sneaker: change value in Sells. 3. Set NULL : Set the sneaker to NULL. 13

  14. Example: Cascade Delete the Nike tuple from Sneakers: Then delete all tuples from Sells that have sneaker= Nike . Update the Sneaker tuple by changing Nike to Adidas in name (for example), Then change all Sells tuples with sneaker= Nike to sneaker= Adidas . 14

  15. Example: Set NULL Delete the Nike tuple from Sneakers: Change all tuples of Sells that have sneaker= Nike to have sneaker= NULL. Update the Nike tuple by changing Nike to Adidas : Same change as for deletion. 15

  16. Choosing a Policy When we declare a foreign key, we may choose policies SET NULL or CASCADE independently for deletions and updates. Follow the foreign-key declaration by: ON [UPDATE, DELETE][SET NULL CASCADE] Two such clauses may be used. Otherwise, the default (reject) is used. 16

  17. Example: Setting Policy CREATE TABLE Sells ( store sneaker price FOREIGN KEY(sneaker) REFERENCES Sneakers(name) ON DELETE SET NULL ON UPDATE CASCADE ); CHAR(20), CHAR(20), REAL, 17

  18. Attribute-Based Checks Constraints on the value of a particular attribute. Add CHECK(<condition>) to the declaration for the attribute. The condition may use the name of the attribute, but any other relation or attribute name must be in a subquery. 18

  19. Example: Attribute-Based Check CREATE TABLE Sells ( store CHAR(20), sneaker CHAR(20) CHECK ( sneaker IN (SELECT name FROM Sneakers)), price REAL CHECK (price <= 50.00) ); /* Subquery is not allowed in sqlite3, one d have to use some trigger, or a straight list to perform the same. */ 19

  20. Example: Attribute-Based Check in SQLite CREATE TABLE Sells ( store sneaker CHECK ( sneaker IN ( Nike , Adidas , AirJordan ), price REAL CHECK (price <= 50.00) ); CHAR(20), CHAR(20) /* Example of Check() that works in SQLite, using a list. */ 20

  21. Timing of Checks Attribute-based checks are performed only when a value for that attribute is inserted or updated. Example: CHECK (price <= 50.00) checks every new price and rejects the modification (for that tuple) if the price is more than $50. Example: CHECK (sneaker IN (SELECT name FROM Sneakers)) not checked if a sneaker is deleted from Sneakers (unlike foreign- keys). 21

  22. Tuple-Based Checks CHECK (<condition>) may be added as a relation-schema element. The condition may refer to any attribute of the relation. But other attributes or relations require a subquery. Checked on insert or update only. 22

  23. Example: Tuple-Based Check Only Joe s Store can sell sneakers for more than $50: CREATE TABLE Sells ( store CHAR(20), sneaker CHAR(20), price REAL, CHECK (store= Joe sStore OR price <= 50.00) ); 23

  24. Assertions These are database-schema elements, like relations or views. Defined by: CREATE ASSERTION <name> CHECK (<condition>); Condition may refer to any relation or attribute in the database schema. /*SQL92 supports assertion, but not sqlite3. Trigger can accomplish the same.*/ 24

  25. Example: Assertion In Sells(sneaker, store, price), no store may charge an average of more than $50. CREATE ASSERTION NoRipoffStors CHECK ( NOT EXISTS ( SELECT store FROM Sells GROUP BY store HAVING 50.00 < AVG(price) )); Stores with an average price above $50 25

  26. Example: Assertion In Buyers(name, addr, phone) and Stores(name, addr, owner), there cannot be more stores than buyers. CREATE ASSERTION FewStore CHECK ( (SELECT COUNT(*) FROM Stores) <= (SELECT COUNT(*) FROM Buyers) ); 26

  27. Timing of Assertion Checks In principle, we must check every assertion after every modification to any relation of the database. A clever system can observe that only certain changes could cause a given assertion to be violated. Example: No change to Sneakers can affect FewStore. Neither can an insertion to Buyers. 27

  28. Triggers: Motivation Assertions are powerful, but the DBMS often can t tell when they need to be checked. Attribute- and tuple-based checks are checked at known times, but are not powerful. Triggers let the user decide when to check for any condition. 28

  29. Event-Condition-Action Rules Another name for trigger is ECA rule, or event-condition-action rule. Event : typically a type of database modification, e.g., insert on Sells. Condition : Any SQL boolean-valued expression. Action : Any SQL statements. 29

  30. Preliminary Example: A Trigger Instead of using a foreign-key constraint and rejecting insertions into Sells(store, sneaker, price) with unknown sneakers, a trigger can add that sneaker to Sneakers, with a NULL manufacturer. 30

  31. Example: Trigger Definition CREATE TRIGGER SneakerTrig AFTER INSERT ON Sells FOR EACH ROW WHEN (New.sneaker NOT IN (SELECT name FROM Sneakers)) BEGIN INSERT INTO Sneakers(name) VALUES(New.sneaker) END; /*new and old references what they are*/ The event The condition The action 31

  32. Options: CREATE TRIGGER CREATE TRIGGER <name> Or: CREATE OR REPLACE TRIGGER <name> Useful if there is a trigger with that name and you want to modify the trigger. 32

  33. Options: The Event AFTER can be BEFORE. Also, INSTEAD OF, if the relation is a view. A clever way to execute view modifications: have triggers translate them to appropriate modifications on the base tables. INSERT can be DELETE or UPDATE. And UPDATE can be UPDATE . . . ON a particular attribute. 33

  34. Options: FOR EACH ROW Triggers are either row-level or statement-level. FOR EACH ROW indicates row-level; its absence indicates statement-level. Row level triggers : execute once for each modified tuple. Statement-level triggers : execute once for a SQL statement, regardless of how many tuples are modified. SQLite doesn t support statement-level 34

  35. Options: REFERENCING INSERT statements imply a new tuple (for row-level) or new table (for statement-level). The table is the set of inserted tuples. DELETE implies an old tuple or table. UPDATE implies both. Refer to these by [NEW OLD][TUPLE TABLE] AS <name> SQLite doesn t support referencing 35

  36. Options: The Condition Any boolean-valued condition. Evaluated on the database as it would exist before or after the triggering event, depending on whether BEFORE or AFTER is used. But always before the changes take effect. Access the new/old tuple/table through the names in the REFERENCING clause. 36

  37. Options: The Action There can be more than one SQL statement in the action. Surround by BEGIN . . . END if there is more than one. But queries make no sense in an action, so we are really limited to modifications. 37

  38. Another Example Using Sells(store, sneaker, price) and a unary relation RipoffStores(store), maintain a list of stores that raise the price of any sneaker by more than $10. 38

  39. The Trigger The event only changes to prices CREATE TRIGGER PriceTrig AFTER UPDATE OF price ON Sells FOR EACH ROW WHEN(New.price > Old.price + 10.00) BEGIN INSERT INTO RipoffStores VALUES(New.store); Condition: a raise in price > $10 We need to consider each price change When the price change is great enough, add the store to RipoffStores 39

  40. Example: Assertion replaced by Trigger In Sells(sneaker, store, price), no store may charge an average of more than $50. We used a Assertion earlier in SQL92. In SQLite, we can use a Trigger to do the same. CREATE Trigger NoRipoffStores BEFORE INSERT on Sells BEGIN SELECT CASE WHEN EXISTS( SELECT store FROM Sells GROUP BY store HAVING 50.00 < AVG(price) ) THEN RAISE ( abort, 'Invalid price...') END; -- select END; -- begin Stores with an average price above $50 40

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#