Title: SQL: Structured Query Language Sequel
1SQL Structured Query Language(Sequel)
2SQL
- Query Language
- Constraints
- Triggers
3Integrity Constraints (Review)
- An IC describes conditions that every legal
instance of a relation must satisfy. - Inserts/deletes/updates that violate ICs are
disallowed. - Can be used to
- ensure application semantics (e.g., sid is a
key), or - prevent inconsistencies (e.g., sname has to be a
string, age must be lt 200) - Types of ICs
- Fundamental Domain constraints, primary
key constraints, foreign key constraints - General constraints Check Constraints, Table
Constraints and Assertions.
4Check or Table Constraints
CREATE TABLE Sailors ( sid INTEGER, sname
CHAR(10), rating INTEGER, age REAL, PRIMARY
KEY (sid), CHECK ( rating gt 1 AND rating
lt 10 )
- Can use queries to express constraint.
5Table Constraints
6Assertions ( Constraints over Multiple Relations)
CREATE TABLE Sailors ( sid INTEGER, sname
CHAR(10), rating INTEGER, age REAL, PRIMARY
KEY (sid), CHECK ( (SELECT COUNT (S.sid)
FROM Sailors S) (SELECT COUNT (B.bid) FROM
Boats B) lt 100 )
Number of boats plus number of sailors is lt 100
- Awkward !
- Wrong?
- Associated with Sailors.
- If Sailors is empty, the number of Boats tuples
can be anything!
7Assertions ( Constraints over Multiple Relations)
Number of boats plus number of sailors is lt 100
CREATE TABLE Sailors ( sid INTEGER, sname
CHAR(10), rating INTEGER, age REAL, PRIMARY
KEY (sid), CHECK ( (SELECT COUNT (S.sid)
FROM Sailors S) (SELECT COUNT (B.bid) FROM
Boats B) lt 100 )
- ASSERTION is the right solution not
associated with either table.
CREATE ASSERTION smallClub CHECK ( (SELECT
COUNT (S.sid) FROM Sailors S) (SELECT COUNT
(B.bid) FROM Boats B) lt 100 )
8Triggers (active database)
- 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)
- A "daemon" that monitors a database
- Row-level trigger statement-level trigger
9Triggers Example (SQL1999)
- CREATE TRIGGER youngSailorUpdate
- AFTER INSERT ON SAILORS
- REFERENCING NEW TABLE NewSailors
- FOR EACH STATEMENT
- INSERT
- INTO YoungSailors(sid, name, age, rating)
- SELECT sid, name, age, rating
- FROM NewSailors N
- WHERE N.age lt 18
10Design of Active Consistent Data
- Triggers are flexible and powerful
- But can be hard to understand
- Several triggers (order?)
- Chain triggers (When to stop?)
- Recursive triggers
- Constraints
- IC achieves same goal
- More opportunity for optimization
- Not restricted into insert/delete/update
11Summary
- SQL allows specification of rich integrity
constraints - Triggers respond to changes in the database