Está en la página 1de 8

Tutorial 5: SQL

By Chaofa Gao Tables used in this note: Sailors(sid: integer, sname: string, rating: integer, age: real); Boats(bid: integer, bname: string, color: string); Reserves(sid: integer, bid: integer, day: date). Sailors Sid 22 29 31 32 58 64 71 74 85 95 Sname Dustin Brutus Lubber Andy Rusty Horatio Zorba Horatio Art Bob Rating 7 1 8 8 10 7 10 9 3 3 Age 45 33 55.5 25.5 35 35 16 40 25.5 63.5 Figure 1: Instances of Sailors, Boats and Reserves bid 101 102 103 104 Boats bname Interlake Interlake Clipper Marine color blue red green red Reserves sid 22 22 22 22 31 31 31 64 64 74 bid 101 102 103 104 102 103 104 101 102 103 day 1998-10-10 1998-10-10 1998-10-8 1998-10-7 1998-11-10 1998-11-6 1998-11-12 1998-9-5 1998-9-8 1998-9-8

1. Create the Tables:
CREATE TABLE sailors ( sid integer not null, sname varchar(32), rating integer, age real, CONSTRAINT PK_sailors PRIMARY KEY (sid) ); CREATE TABLE reserves ( sid integer not null, bid integer not null, day datetime not null, CONSTRAINT PK_reserves PRIMARY KEY (sid, bid, day), FOREIGN KEY (sid) REFERENCES sailors(sid), FOREIGN KEY (bid) REFERENCES boats(bid) );

0 ) INSERT INTO reserves ( sid. year() and day() functions.5 63. bid.2.5 35 35 16 35 25.5 25. S. SELECT S. '1998-10-10') Note the date can have one of the following formats: yyyy-mm-dd.5 or SELECT S.5 33 45 35 55. mm-dd-yyyy and mm/dd/yyyy In addition. age ) VALUES ( 22. Simple SQL Query The basic form of an SQL query: SELECT [DISTINCT] select-list FROM from-list WHERE qualification Ex1: Using DISTINCT Sname Dustin Brutus Lubber Andy Rusty Horatio Zorba Horatio Art Bob age 45 33 55.sname. 7. day ) VALUES ( 22. 'Dustin'.5 25. 45. sname. DB2 allows to parse the date attribute using its month().age FROM sailors S SELECT sname. Insert Data INSERT INTO sailors ( sid.* FROM Sailors S. e.g.5 35 16 SELECT DISTINCT S.sname. age FROM sailors sname Andy Art Bob Brutus Dustin Horatio Lubber Rusty Zorba age 25. Find all information of sailors who have reserved boat number 101.5 63. 101.age FROM sailors AS S Ex2. Reserves R . select * from reserves where year(day) = 1998 and month(day) = 10 3. rating. S.

day AND R1. and list in the order of age.bid = 103 Or without using the range variables. Reserves WHERE Sailors.sid = Reserves.age [ASC] ORDER BY S. along with the use of symbols: % (which stands for zero or more arbitrary characters) and _ (which stands for exactly one.sid = R.age FROM Sailors S.day = R2.sid AND R.sid = R.age ORDER BY S. S. Ex3.sname.bid AND B.sid = R1. Reserves R2 WHERE S. Find the names of sailors who have reserved at least one boat. characters) .sname FROM Sailors S. SELECT sname. S and R SELECT Sailors. Find the names of sailors who have reserved a red boat.sid AND S. SELECT DISTINCT S. the sailor has made some reservation.bid <> R2.sid AND R1.age DESC (default) Ex4. arbitrary. Reserves R WHERE S.sid. SELECT sname FROM Sailors S.sid AND Reserves.bid Ex6.* FROM Sailors. Boats B WHERE S.sid = R2.bid = B. age. rating + 1 as sth FROM Sailors WHERE 2* rating –1 < 10 AND sname like ‘ B_%b’ SQL provides for pattern matching through LIKE operator.sid The join of Sailors and Reserves ensure that for each select sname.color = ‘ red’ ORDER BY S. S.sid AND R.bid = 103 * can be used if you want to retrieve all columns.sid = R. SELECT S. Reserves R1.WHERE S. Using Expressions and Strings in the SELECT Command. Reserves R. Ex5. Find the ids and names of sailors who have reserved two different boats on the same day.

sid FROM Boats B. Replace UNION with UNION ALL.4. The answer contains: 22 31 74 22 31 64 22 31 Replace UNION with INTERSECT.bid = B2. Find the ids of sailors who have reserved a red boat or a green boat.bid = 103 ) The inner subquery has been completely independent of the outer query. use UNION ALL. Reserves R WHERE R. Ex7. Intersect and Except Note that Union.bid AND B.color = ‘ red’ UNION SELECT R2.sid IN ( SELECT R.bid = B. Union. SELECT R. To retain duplicates. 6. that is.sname FROM Sailors S WHERE S. have the same number of columns and the columns. have the same types. Intersect and Except can be used on only two tables that are union-compatible. Reserves R2 WHERE R2. . The answer contains just the id 64. Nested Query IN and NOT IN EXISTS and NOT EXISTS UNIQUE and NOT UNIQUE op ANY op ALL EX8: Find the names of sailors who have reserved boat 103. SELECT S. Replace UNION with EXCEPT. taken in order.color = ‘ green’ The answer contains: SID----------22 31 64 74 The default for UNION queries is that duplicates are eliminated.bid AND B2.sid FROM Boats B2.sid FROM Reserves R WHERE R. The answer contains: 22 31.

EX11: Find the names of sailors who have reserved all boats.bid = 103 AND R.sname.bid FROM Reserves R .sid = S.rating FROM Sailors S2 WHERE S2.sid )) An alternative solution: SELECT S.sname FROM Sailors S WHERE NOT EXISTS ( ( SELECT B. respectively.rating FROM Sailors S WHERE S.rating > ANY ( SELECT S2.bid FROM Boats B) EXCEPT ( SELECT R.sid = S. SELECT S. SELECT S.sname FROM Sailors S WHERE EXISTS ( SELECT * FROM Reserves R WHERE R. S. S.age <= ALL ( SELECT age FROM Sailors ) EX10: Find the names and ratings of sailor whose rating is better than some sailor called Horatio. EX9: Find the name and the age of the youngest sailor.bid FROM Reserves R WHERE R.sname = ‘ Horatio’ ) Note that IN and NOT IN are equivalent to = ANY and <> ALL.bid FROM Boats B WHERE NOT EXISTS ( SELECT R.sname. SELECT S.age FROM Sailors S WHERE S.(Correlated Nested Queries) SELECT S.sid ) The inner query depends on the row that is currently being examined in the outer query.sname FROM Sailors S WHERE NOT EXISTS ( SELECT B.

SELECT COUNT( DISTINCT S. AVG(S.rating 3 44. EX12: Count the number of different sailor names.rating.5 7 8 9 10 40 40. S. Rating avg_age SELECT S.age) FROM Sailors S2 ) SELECT [DISTINCT] select-list FROM from-list WHERE qualification GROUP BY grouping-list HAVING group-qualification EX15: Find the average age of sailors for each rating level.age = (SELECT MIN(S2.bid = B. SUM ([DISTINCT] A): The sum of all (unique) values in the A column.bid AND R.age) AS avg_age FROM Sailors S 1 33 GROUP BY S.sid = S. SELECT AVG(s.sname.sid ) ) 7.5 35 25.age) FROM Sailors S EX14: Find the name and the age of the youngest sailor.sname ) FROM Sailors S EX13: Calculate the average age of all sailors.age FROM Sailors S WHERE S. MAX (A): The maximum value in the A column.WHERE R. MIN (A): The minimum value in the A column. AVG ([DISTINCT] A): The average of all (unique) values in the A column.5 . SELECT S. Aggregation Operators COUNT ([DISTINCT] A): The number of (unique) values in the A column.

* and / all return null if one of their arguments is null. 'Dan'. or both contain null.age) as avg_age FROM Sailors S 3 63. age ) VALUES ( 99. SUM.rating HAVING COUNT(*) > 1 EX16: An example shows difference between WHERE and HAVING: Rating avg_age SELECT S.rating 8 55. rating. (If we compare two null values using =. and variations using DISTINCT) simply discard null values After: INSERT INTO sailors ( sid. NULL value and OUTER JOIN In the presence of null values. MIN. All the other aggregate operations (COUNT.rating. MAX.5 40 40.rating.EX16: Find the average age of sailors for each rating level that has at least two sailors.age) as avg_age FROM Sailors S GROUP BY S.age) >= 40 5. 48.5 SELECT S.age) AS avg_age FROM Sailors S GROUP BY S. any row that evaluates to false or to unknown is elim inated The two rows are duplicates if corresponding columns are either equal. the result is unknown) The arithmetic operation +. A VG(S. Rating 3 7 8 10 avg_age 44.age >=40 7 45 GROUP BY S.5 Rating 3 7 8 avg_age 44. AVG.5 WHERE S.5 40 40.5 25.0 ) . AVG(S. -. AVG(S.rating HAVING AVG(S.5 SELECT S. null. Count(*) handle null values just like other values.rating. sname. will return 11 will return 10 will return 11 SELECT COUNT(*) FROM Sailors SELECT COUNT(rating) FROM Sailors SELECT COUNT(age) FROM Sailors .

sid ORDER BY sailors. sailors.sid.bid FROM sailors LEFT OUTER JOIN reserves ON reserves. reserves.sid = sailors.sname.sid sid 22 22 22 22 29 31 31 31 32 58 64 64 71 74 85 95 99 sname Dustin Dustin Dustin Dustin Brutus Lubber Lubber Lubber Andy Rusty Horatio Horatio Zorba Horatio Art Bob Dan bid 101 102 103 104 102 103 104 101 102 103 .An example of OUTER JOIN: SELECT sailors.