Download presentation
Presentation is loading. Please wait.
1
SQL: Queries, Programming, Triggers
Chapter 5 The slides for this text are organized into chapters. This lecture covers Chapter 5. Chapter 1: Introduction to Database Systems Chapter 2: The Entity-Relationship Model Chapter 3: The Relational Model Chapter 4 (Part A): Relational Algebra Chapter 4 (Part B): Relational Calculus Chapter 5: SQL: Queries, Programming, Triggers Chapter 6: Query-by-Example (QBE) Chapter 7: Storing Data: Disks and Files Chapter 8: File Organizations and Indexing Chapter 9: Tree-Structured Indexing Chapter 10: Hash-Based Indexing Chapter 11: External Sorting Chapter 12 (Part A): Evaluation of Relational Operators Chapter 12 (Part B): Evaluation of Relational Operators: Other Techniques Chapter 13: Introduction to Query Optimization Chapter 14: A Typical Relational Optimizer Chapter 15: Schema Refinement and Normal Forms Chapter 16 (Part A): Physical Database Design Chapter 16 (Part B): Database Tuning Chapter 17: Security Chapter 18: Transaction Management Overview Chapter 19: Concurrency Control Chapter 20: Crash Recovery Chapter 21: Parallel and Distributed Databases Chapter 22: Internet Databases Chapter 23: Decision Support Chapter 24: Data Mining Chapter 25: Object-Database Systems Chapter 26: Spatial Data Management Chapter 27: Deductive Databases Chapter 28: Additional Topics 3/21/2020
2
Example Schema We will use these table definitions in our examples.
Sailors(sid: integer, sname: string, rating: integer, age: real) Boats(bid: integer, bname: string, color: string) Reserves(sid: integer, bid: integer, day: date) Make reservations
3
Basic SQL Query SELECT [DISTINCT] target-list FROM relation-list
WHERE qualification relation-list A list of relation names target-list A list of attributes of relations in relation-list qualification Comparisons (“Attr op const” or “Attr1 op Attr2,” where op is one of ˂, ˃, ≤, ≥, =, ≠ ) combined using AND, OR, and NOT. DISTINCT is an optional keyword indicating that the answer should not contain duplicates.
4
Querying Relations (1) What does the following query compute? Enrolled
Range variable Enrolled SELECT S.name, E.cid FROM Students S, Enrolled E WHERE S.sid=E.sid AND E.grade=“A” “S.sid” means “sid” is in S, i.e., sid is a student “E.sid” means ”sid” is in E, i.e., sid has enrolled in a course Students sid name login age gpa 53831 Zhang 19 3.2 53650 Smith 21 3.9 53666 Jones 20 3.5
5
Querying Relations (1) What does the following query compute? Enrolled
Range variable Enrolled SELECT S.name, E.cid FROM Students S, Enrolled E WHERE S.sid=E.sid AND E.grade=“A” Since this specific “sid” is in both Students and Enrolled, “sid” is a student who has enrolled in a course. Students sid name login age gpa 53831 Zhang 19 3.2 53650 Smith 21 3.9 53666 Jones 20 3.5
6
Retrieve names of students and the courses they received an “A” grade
Querying Relations (1) What does the following query compute? Range variable Enrolled SELECT S.name, E.cid FROM Students S, Enrolled E WHERE S.sid=E.sid AND E.grade=“A” A student with “sid” has an entry in Enrolled The Enrolled entry has a grade of “A” Students sid name login age gpa 53831 Zhang 19 3.2 53650 Smith 21 3.9 53666 Jones 20 3.5 Retrieve names of students and the courses they received an “A” grade
7
Querying Relations (2) Enrolled Students SELECT S.name, E.cid
sid name login age gpa 53831 Zhang 19 3.2 53650 Smith 21 3.9 53666 Jones 20 3.5 SELECT S.name, E.cid FROM Students S, Enrolled E WHERE S.sid=E.sid AND E.grade=“A” S.name E.cid Smith Topology112
8
A Note on Range Variables
Really needed only if the same relation appears twice in the FROM clause. The previous query can be written in two ways: Range variable SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103 It is good style, however, to use range variables always! SELECT sname FROM Sailors, Reserves WHERE Sailors.sid=Reserves.sid AND bid=103 OR
9
Semantics of SQL Query Result ˂, ˃, ≤, ≥, =, ≠ R1 × R2 × R3 × · · ·
QUERY PROCESSOR SELECT [DISTINCT] target-list FROM relation-list WHERE qualification target-list Define search space relation-list R1 × R2 × R3 × · · · qualification This strategy is probably the least efficient way to compute a query! An optimizer will find more efficient strategies to compute the same answers. Select rows ˂, ˃, ≤, ≥, =, ≠ Query Result Select columns Projection
10
Conceptual Evaluation Strategy
Semantics of an SQL query defined in terms of the following conceptual evaluation strategy: Compute the cross-product of relation-list. Discard resulting tuples if they fail qualifications. Delete attributes that are not in target-list. If DISTINCT is specified, eliminate duplicate rows. 3/21/2020
11
Example of Conceptual Evaluation
SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103 S×R (sid) sname rating age bid day 22 dustin 7 45.0 101 10/10/96 58 103 11/12/96 31 lubber 8 55.5 rusty 10 35.0 Remove Irrelevant columns Disqualified Answer
12
SQL vs Domain Relational Calculus
SELECT [DISTINCT] target-list FROM relation-list WHERE qualification 3/21/2020
13
Find sailors who’ve reserved at least one boat
Sailors(sid, sname, rating, age) Reserves(sid, bid, day) sid has a reservation SELECT S.sid FROM Sailors S, Reserves R WHERE S.sid = R.sid Given a sailor sid sid has a reservation 3/21/2020
14
Find sailors who’ve reserved at least one boat
SELECT S.sid FROM Sailors S, Reserves R WHERE S.sid = R.sid Would adding DISTINCT to this query make a difference? Remove duplicate sid (with reservations for different boats) What is the effect of replacing S.sid by S.sname in the SELECT clause? Since two sailors may have the same name, some sailor may have no reservation even his/her name is in the output 3/21/2020
15
Arithmetic Expressions and Strings
AS and = are two ways to name fields in result SELECT S.age, age1 = S.age-5, 2*S.age AS age2 FROM Sailors S WHERE S.sname LIKE ‘B_%B’ Name begins and ends with ‘B’ and contains at least three characters LIKE is used for string matching. ‘_ ’ stands for any one character and ‘%’ stands for 0 or more arbitrary characters. 3/21/2020
16
Find names of sailors who’ve reserved a red or a green boat
Sailors(sid, sname, rating, age) Reserves(sid, bid, day) Boats(bid, bname, color) sid has a reservation for bid bid is a boat color = ‘red’ OR color = ‘green’ SELECT S.name FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND (B.color=‘red’ OR B.color=‘green’)
17
Find names of sailors who’ve reserved a red or a green boat
Name of sailors who’ve reserved red boats SELECT S.name FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ UNION AND B.color=‘green’ Name of sailors who’ve reserved green boats UNION: Compute the union of any two union-compatible sets of tuples (which are themselves the result of SQL queries).
18
EXCEPT What do we get if we replace UNION by EXCEPT?
SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ EXCEPT AND B.color=‘green’ Name of sailors who’ve reserved red boats Name of sailors who’ve reserved green boats What do we get if we replace UNION by EXCEPT? Find the sids of all sailors who have reserved red boats but not green boats
19
Find names of sailors who’ve reserved a red and a green boat
20
Find names of sailors who’ve reserved a red and a green boat
Sailors(sid, sname, rating, age) Reserves(sid, bid, day) Boats(bid, bname, color) bid is a boat sid has a reservation for bid ‘red’ Reserves(sid, bid, day) Boats(bid, bname, color) That bid is a boat sid also has a reservation for another bid ‘green’ R1 R2 B1 B2 SELECT S.name FROM Sailors S, Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE S.sid=R1.sid AND R1.bid=B1.bid The sailor reserves 1st boat AND S.sid=R2.sid AND R2.bid=B2.bid The same sailor reserves 2nd boat AND (B1.color=‘red’ AND B2.color=‘green’)
21
Find names of sailors who’ve reserved a red and a green boat
Can’t we say: SELECT S.name FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND (B.color=‘red’ AND B.color=‘green’) No boat has two colors → Result is empty !
22
Find names of sailors who’ve reserved a red and a green boat
SELECT S.name FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ INTERSECT AND B.color=‘green’ Name of sailors who’ve reserved red boats Name of sailors who’ve reserved green boats INTERSECT: Can be used to compute the intersection of any two union-compatible sets of tuples. Included in the SQL/92 standard, but some systems don’t support it.
23
Sailor S has at least one of these reservations
Nested Queries Find names of sailors who’ve reserved boat #103 SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid=103) All “boat 103” reservations Sailor S has at least one of these reservations 3/21/2020
24
Nested Queries Find names of sailors who’ve reserved boat #103
SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid=103) All “boat 103” reservations Think of a nested loops evaluation: For each Sailors tuple, check the qualification by computing the subquery. 3/21/2020
25
Nested Queries Find names of sailors who’ve reserved boat #103
SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid=103) All “boat 103” reservations A very powerful feature of SQL: a WHERE clause can itself contain an SQL query! (Actually, so can FROM and HAVING clauses.) To find sailors who’ve not reserved #103, use NOT IN. 3/21/2020
26
Nested Queries with Correlation (1)
Query: Find names of sailors who’ve reserved boat #103 EXISTS tests whether a set is nonempty. SELECT S.sname FROM Sailors S WHERE EXISTS (SELECT * FROM Reserves R WHERE S.sid=R.sid AND R.bid=103) S Sailor S reserves boat 103 3/21/2020
27
NOT EXIST SELECT S.sname FROM Sailors S WHERE NOT EXISTS (SELECT * FROM Reserves R WHERE R.bid=103 AND S.sid=R.sid) Use NOT EXIST to find the names of sailors who have not reserved a red boat 3/21/2020
28
Nested Queries with Correlation (2)
Query: Find names of sailors who reserve boat 103 at most once. SELECT S.sname FROM Sailors S WHERE UNIQUE (SELECT R.bid FROM Reserves R WHERE R.bid=103 AND S.sid=R.sid) Reservations for boat 103 by sailor “sid” “at most once” UNIQUE returns true if no row appears more than once. (Note: returns true if answer is empty) Can we replace “SELECT R.bid” by “ SELECT * ” ? No, A sailor may reserve boat 103 on different days; and UNIQUE would return true 3/21/2020
29
More on Set-Comparison Operators
Also available: op ANY, op ALL , where op: ˃, ˂, =, ≠, ≥, ≤ Example: “Find sailors whose rating is greater than that of some sailor called Horatio” SELECT * FROM Sailors S WHERE S.rating > ANY (SELECT S2.rating FROM Sailors S2 WHERE S2.sname=‘Horatio’) The subquery must return a row that makes the comparison true, in order for S.rating > ANY … to return true 3/21/2020
30
Rewriting INTERSECT Queries Using IN
Find sid’s of sailors who’ve reserved both a red and a green boat: sid of sailors who’ve reserved red boats SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ (SELECT S2.sid FROM Sailors S2, Boats B2, Reserves R2 WHERE S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color=‘green’) Similarly, we can rewrite EXCEPT queries using NOT IN. AND S.sid IN sid of sailors who’ve reserved green boats 3/21/2020
31
Division Operations in SQL (1)
Find names of sailors who’ve reserved all boat: SELECT S.sname FROM Sailors S WHERE NOT EXIST ((SELECT B.bid FROM Boats B) EXCEPT (SELECT R.bid FROM Reserves R WHERE R.sid = S.sid )) The sailor reserved all boats All boats Boats not reserved by the sailor All boats reserved by the sailor 3/21/2020
32
Division Operations in SQL (2)
Find names of sailors who’ve reserved all boat: Sailor S SELECT S.sname FROM Sailors S WHERE NOT EXIST ((SELECT B.bid FROM Boats B WHERE NOT EXISTS (SELECT R.bid FROM Reserves R WHERE R.bid = B.bid AND R.sid = S.sid)) such that there is no boat B without a reservation showing Sailor S such that … there is no boat B without … a Reserves tuple showing S reserved B. Sailor S reserved boat B 3/21/2020
33
Aggregate Operators Significant extension of relational algebra
COUNT (*) The number of rows in the relation COUNT ([DISTINCT] A) The number of (unique) values in the A column SUM ([DISTINCT] A) The sum of all (unique) values in the A column AVG ([DISTINCT] A) The average of all (unique) values in the A column MAX (A) The maximum value in the A column MIN (A) The minimum value in the A column MAX(A) A 5 7 12 4 17 The number of rows in the relation
34
Find the average age of sailors with a rating of 10
Aggregate Operation Sailors 32 Aggregator Qualifier 2 Find the average age of sailors with a rating of 10 1 SELECT AVG (S.age) FROM Sailors S WHERE S.rating=10
35
Aggregate Operators SELECT COUNT (*) FROM Sailors S 2
Count the number of sailors SELECT AVG (S.age) FROM Sailors S WHERE S.rating=10 Find sailors with a rating of 10 Compute their average age 1 2 Compute the average age of sailors with a rating of 10 SELECT COUNT (DISTINCT S.rating) FROM Sailors S WHERE S.sname=‘Bob’ Find sailors called ‘Bob’ Count their number of distinct ratings 1 2 Count the number of distinct ratings of sailors called “Bob”
36
Aggregate Operators SELECT S.sname FROM Sailors S 1
WHERE S.rating= (SELECT MAX(S2.rating) FROM Sailors S2) Find the name of sailors with the highest rating Compute maximum rating 1 2 SELECT AVG (DISTINCT S.age) FROM Sailors S WHERE S.rating=10 Select all sailors with a rating of 10 Find the average of the distinct ages of these sailors Find the average of the distinct ages of sailors with a ratio of 10 1 2
37
Find names of sailors with the highest rating
Comparing a number with a relation is allowed here SELECT S.sname FROM Sailors S WHERE S.rating = (SELECT MAX(S2.rating) FROM Sailors S2) Allowed in SQL/92 standard, but is not supported in some systems SELECT S.sname FROM Sailors S WHERE ( SELECT MAX (S2.rating) FROM Sailors S2 ) = S.rating
38
Find name and age of the oldest sailor(s)
Only aggregate operations allowed Illegal SELECT S.sname, MAX (S.age) FROM Sailors S If the SELECT clause uses an aggregate operation, then it must use only aggregate operations unless the query contains a GROUP BY clause (next slide)
39
GROUP BY and HAVING So far, we’ve applied aggregate operators to all (qualifying) tuples. Sometimes, we want to apply them to each of several groups of tuples. Relation Aggregator Qualifier 32 Relation Group 1 Aggregator 12 Group 2 Group 3 9 11
40
GROUP BY and HAVING (2) Consider: Find the age of the youngest sailor for each rating level. /* Min(age) for multiple groups If we know that rating values go from 1 to 10, we can write 10 queries that look like this: In general, we don’t know how many rating levels exist, and what the rating values for these levels are ! SELECT MIN (S.age) FROM Sailors S WHERE S.rating = i For i = 1, 2, ... , 10: 3/21/2020
41
Queries With GROUP BY and HAVING
SELECT [DISTINCT] target-list FROM relation-list WHERE qualification GROUP BY grouping-list HAVING group-qualification e.g., MIN(Attribute) Evaluated on a per-group basis HAVING GROUP BY Output a table Aggregator 12 9 Qualifier selecting groups Group 1 Group 2 Group 3 SELECT FROM WHERE
42
Grouping-list Grouping-list
Attributes of the grouping-list should also appear in the SELECT clause SELECT S.rating, MIN (S.age) FROM Sailors S GROUP BY S.rating Grouping-list A group is a set of tuples that have the same value for all attributes in grouping-list
43
Conceptual Evaluation
SELECT [DISTINCT] target-list FROM relation-list WHERE qualification GROUP BY grouping-list HAVING group-qualification Conceptual Evaluation The cross-product of relation-list is computed Tuples that fail qualification are discarded `Unnecessary’ fields are deleted The remaining tuples are partitioned into groups by the value of attributes in grouping-list. The group-qualification is then applied to eliminate some groups One answer tuple is generated per qualifying group 3/21/2020
44
Find the age of the youngest sailor with age ≥ 18, for each rating with at least 2 such sailors
SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age >= 18 GROUP BY S.rating HAVING COUNT (*) > 1 Input relation Sailors age Answer Disqualified Only one group satisfies HAVING 4 rating groups Only S.rating and S.age are mentioned in SELECT
45
Find the age of the youngest sailor with age ≥ 18
“GROUP BY and HAVING” Examples Find the age of the youngest sailor with age ≥ 18 SELECT MIN (S.age) FROM Sailors S WHERE S.age >= 18 SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age >= 18 GROUP BY S.rating Find the age of the youngest sailor with age ≥ 18, for each rating SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age >= 18 GROUP BY S.rating HAVING COUNT (*) > 1 Find the age of the youngest sailor with age ≥ 18, for each rating with at least 2 such sailors
46
For each red boat, find the number of reservations for this boat
3) Count the number of reservations for each red boat SELECT B.bid, COUNT (*) AS scount FROM Boats B, Reserves R WHERE R.bid=B.bid AND B.color=‘red’ GROUP BY B.bid 1) Find all reservations for red boats 2) Group the reservations for red boats according to bid 3/21/2020
47
Illegal Having Clause Illegal !
HAVING clause is to select groups; but B.Color is not in grouping-list Illegal Having Clause SELECT B.bid, COUNT (*) AS scount FROM Boats B, Reserves R WHERE R.bid=B.bid GROUP BY B.bid HAVING B.color=‘red’ Illegal ! HAVING B.color=‘red’ Having clause is to select groups; but B.Color is not in grouping-list GROUP BY “bid” Output a table HAVING “red” ? Aggregator ? Qualifier selecting groups Group 1 Group 2 Group 3 SELECT FROM WHERE 3/21/2020
48
Needs aggregate function
Find the age of the youngest sailor older than 18, for each rating with at least 2 sailors Step 1: Select the desired tuples (using WHERE) Step 2: Form the groups (using GROUP BY) Step 3: Select the desired groups (using HAVING) Step 4: Compute the aggregation for each group (using COUNT, MAX, AVG, etc.) 3/21/2020
49
4 1 Find the age of the youngest sailor older than 18, for each rating with at least 2 sailors 2 3 HAVING 1 ˂ (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating) 3 Sailors Rating Age>18 Group S.rating Size>1 1 WHERE S.age > 18 Min. age 22 26 2 GROUP BY S.rating 4 MIN(S.age) 3/21/2020
50
4 1 Find the age of the youngest sailor older than 18, for each rating with at least 2 sailors 2 3 HAVING 1 ˂ (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating) 1 2 3 4 SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age > 18 GROUP BY S.rating HAVING 1 ˂ (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating) WHERE S.age > 18 GROUP BY S.rating MIN(S.age) 3/21/2020
51
Number of sailors with this rating
Find the age of the youngest sailor older than 18, for each rating with at least 2 sailors 4) Find youngest age for each qualified group 1) Find all sailors older than 18 SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age > 18 GROUP BY S.rating HAVING 1 ˂ (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating) 2) Group qualified sailors according to rating 3.2) Discard groups with less than two sailors 3.1) Count the number of sailors in a group Number of sailors with this rating 3/21/2020
52
Find the age of the youngest sailor older than 18 for each rating that has at least 2 sailors
SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age > 18 GROUP BY S.rating HAVING 1 ˂ (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating) Find the age of the youngest sailor older than 18 for each rating level that has at least two such sailors (MORE IN NEXT PAGE) What if HAVING clause is replaced by “HAVING COUNT(*) > 1” ? 3/21/2020
53
Find the age of the youngest sailor older than 18 for each rating that has at least 2 sailors
Counting includes sailors younger than 18 SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age > 18 GROUP BY S.rating HAVING 1 ˂ (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating) “age” is not mentioned in this subquery At least 2 sailors SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age > 18 GROUP BY S.rating HAVING COUNT (*) › 1 Find the age of the youngest sailor older than 18, for each rating level that has at least two such sailors Counting only adult sailors At least 2 such sailors, i.e., older than 18 3/21/2020
54
Find the age of the youngest sailor older than 18, for each rating that has at least 2 sailors
SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age > 18 GROUP BY S.rating HAVING 1 ˂ (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating) HAVING clause can contain a subquery We can use S.rating here because it has a single value for the current group of sailors. 3/21/2020
55
Aggregate operations cannot be nested
Find those ratings for which the average age is the minimum over all ratings Aggregate operations cannot be nested SELECT S.rating FROM Sailors S WHERE S.age = (SELECT MIN (AVG (S2.age)) FROM Sailors S2) 3/21/2020
56
Find those ratings for which the average age is the minimum over all ratings
Find average age for each rating group Temp rating avgage SELECT Temp.rating, Temp.avgage FROM (SELECT S.rating, AVG (S.age) AS avgage FROM Sailors S GROUP BY S.rating) AS Temp WHERE Temp.avgage = (SELECT MIN (Temp.avgage) FROM Temp) Average age for some rating group Minimum over all ratings 3/21/2020
57
Null Values Field values in a tuple are sometimes
unknown (e.g., a rating has not been assigned), or inapplicable (e.g., no spouse’s name). SQL provides a special value null for such situations. 3/21/2020
58
Null Values The presence of null complicates many issues:
Special operators needed, e.g., IS NULL to test if a value is null. Is rating>8 true or false when rating is equal to null? null What about AND, OR and NOT ? Need a 3-valued logic (true, false, and unknown), e.g., (unknown OR false) = unknown. Meaning of constructs must be defined carefully, e.g., WHERE clause eliminates rows that don’t evaluate to true. Null + 5 = null; but SUM (null, 5) = 5. (nulls can cause some unexpected behavior) New operators (in particular, outer joins) possible/needed (next slide). 3/21/2020
59
Outer Joins S1 R1 S1 R1 22 dustin 7 45.0 101 10/10/96 31 lubber 8
sid sname rating age bid day 22 dustin 7 45.0 101 10/10/96 31 lubber 8 55.55 null 58 rusty 10 35.0 103 11/12/96 No match in R1 3/21/2020
60
INSERT Command INSERT INTO Sailors (sid, sname, rating, age)
VALUES (257, ‘John Smith’, 7, 32) INSERT INTO Sailors INSERT INTO YoungSailors SELECT * FROM Sailors S WHERE S.age < 19 Must know the order of the attributes All young sailors are copied from Sailors to YoungSailors 3/21/2020
61
Delete all young sailors
DELETE Command DELETE FROM Sailors WHERE sid = 257 WHERE age < 19 Delete one tuple Delete all young sailors Delete all tuples 3/21/2020
62
UPDATE Command Sailors UPDATE Sailors SET rating = 7 WHERE sid = 24
sname rating age 12 dustin 9 19 24 brandon 6 27 36 emily 7 32 45 trevor 21 UPDATE Sailors SET rating = 7 WHERE sid = 24 UPDATE Employees SET salary = salary * 1.03 WHERE dno = 24 Modify the rating level for sailor 24 to “7” Give employees of Department 24 a 3% raise 3/21/2020
63
Integrity Constraints (Review)
An IC describes conditions that every legal instance of a relation must satisfy. Inserts/deletes/updates that violate IC’s 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 < 200) Types of IC’s: Domain constraints, primary key constraints, foreign key constraints, general constraints. Domain constraints: Field values must be of right type. Always enforced. 3/21/2020 5
64
A general constraint 1 ≤ rating ≤ 10
CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( rating >= 1 AND rating <= 10 ) ); A general constraint 1 ≤ rating ≤ 10 Useful when more general ICs than keys are involved. 8
65
General Constraint A CHECK constraint can be created for multiple attributes: CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( sid > 0 AND age <= 75 ) ); 8
66
Named General Constraints
Convenient to have a named constraint, e.g., delete it later: ALTER TABLE RESERVES DROP CHECK noInterlakeRes CREATE TABLE Reserves ( sname CHAR(10), bid INTEGER, day DATE, PRIMARY KEY (bid,day), CONSTRAINT noInterlakeRes CHECK (`Interlake’ <> ( SELECT B.bname FROM Boats B WHERE B.bid=bid))); A general constraint can be named For each boat Find the name of the boat - Can use queries to express constraint 8
67
Column Constraint vs. Table Constraint
CREATE TABLE Employees ( eid INTEGER, name CHAR(10), startdate DATE enddate DATE salary INTEGER CHECK ( salary < ), PRIMARY KEY (eid), CONSTRAINT chk_date CHECK ( startdate <= enddate) ); Column constraint Table constraint may reference multiple columns 8
68
Adding a CHECK Constraint
To create a CHECK constraint after the table is already created: ALTER TABLE Sailors ADD Constraint CHK_Age CHECK (Age <= 75) Optional 8
69
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) < 100 ) Number of boats plus number of sailors is < 100 This is not checked in Boats. If it is not modified, the number of Boats tuples can be anything Awkward and wrong! CREATE ASSERTION smallClub CHECK ( (SELECT COUNT (S.sid) FROM Sailors S) + (SELECT COUNT (B.bid) FROM Boats B) < 100 ) ASSERTION is the right solution; not associated with either table 9
70
Triggers Trigger is a procedure that starts automatically if specified changes occur to the DBMS Three parts Event A change to the database that activates the trigger (e.g., BEFORE insert, AFTER update) Condition A query or test that is run when the trigger is activated (e.g., WHEN total salaries > $1M) Action A procedure that is executed when the trigger is activated and its condition is true Condition Action Event 3/21/2020
71
Specify Action The action can be executed before, after, or instead of the triggering event BEFORE The action is executed before the event that triggered the action AFTER The action is executed after the triggering event INSTEAD OF The action is executed and the triggering event is never executed (1) Event trigger (2) Action 3/21/2020
72
UPDATE Employees SET salary = salary * 1.3 WHERE dno = 24
An SQL INSERT/DELETE/UPDATE statement may affect multiple rows of a table UPDATE Employees SET salary = salary * 1.3 WHERE dno = 24 3/21/2020
73
Two kinds of triggers An SQL INSERT/DELETE/UPDATE statement may affect multiple rows of a table Statement-level trigger: executed once for all the tuples that are changed in one SQL statement. REFERENCING NEW TABLE AS newtuples, /* Set of new tuples OLD TABLE AS oldtuples /* Set of old tuples Row-level trigger: executed once for each modified tuple. REFERENCING OLD AS oldtuple, NEW AS newtuple newtuples, oldtuple, newtuple can be used in the CONDITION and ACTION clauses 3/21/2020
74
Trigger Examples (SQL:1999)
Event CREATE TRIGGER InitCounter BEFORE INSERT ON SAILORS FOR EACH STATEMENT INSERT INTO CountTable SET count = 0 WHERE age = 18 CREATE TRIGGER IncrCount AFTER INSERT ON SAILORS FOR EACH ROW UPDATE CountTable SET count = count + 1 CountTable age count 17 113 18 . 99 2 Statement-level trigger: Need to initialize counter only once Event CountTable age count 17 113 18 229 . 99 2 Row-level trigger: evaluate each new sailor to decide whether to increment the counter 3/21/2020
75
Statement-Level Trigger Example (SQL:1999)
Maintain information on young sailors in a separate YoungSailors table Give a table name to the set of newly inserted tuples OLD TABLE declaration is not needed for INSERT operation CREATE TRIGGER youngSailorUpdate AFTER INSERT ON SAILORS /* Event REFERENCING NEW TABLE AS NewSailors FOR EACH STATEMENT /* Statement-level trigger (default) INSERT /* Action INTO YoungSailors(sid, name, age, rating) SELECT sid, name, age, rating FROM NewSailors N WHERE N.age <= 18 New tuples Insert Sailors NewSailors TRIGGER ≤ 18 YoungSailors 3/21/2020
76
Row-Level Trigger Example (SQL:1999)
Sailors(SID, sname, rating, age) CREAT TRIGGER RatingTrigger AFTER UPDATE OF rating ON Sailors REFERENCING OLD AS OldTuple, /* value before update NEW AS NewTuple /* value after update WHEN (OldTupple.rating ˃ NewTupple.rating) FOR EACH ROW UPDATE Sailors SET rating = OldTuple.rating WHERE SID = NewTuple.SID /* Event /* Condition /* Row-level trigger /* Action: Restore /* any attempt to /* lower rating 3/21/2020
77
Summary SQL was an important factor in the early acceptance of the relational model; more natural than earlier procedural query languages. Relationally complete; in fact, significantly more expressive power than relational algebra. Even queries that can be expressed in relational algebra can often be expressed more naturally in SQL. Many alternative ways to write a query; optimizer should look for most efficient evaluation plan. In practice, users need to be aware of how queries are optimized and evaluated for best results. 3/21/2020
78
Summary (Contd.) NULL for unknown-field values brings many complications SQL allows specification of rich integrity constraints Triggers respond to changes in the database 3/21/2020
79
Midterm Chapters 1, 2, 3, 4, 5 Date: February 26, 2019
How to prepare ? Study the slides Prepare one page of notes (may be used during the exam) Practice the Algebra, Calculus, and SQL examples Practice the homeworks 3/21/2020
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.