MIS Database Systems SQL: Queries, Constraints, Triggers

Size: px
Start display at page:

Download "MIS Database Systems SQL: Queries, Constraints, Triggers"

Transcription

1 MIS Database Systems SQL: Queries, Constraints, Triggers Ahmet Onur Durahim

2 Learning Objectives Basics of SQL Conceptual Evaluation of SQL Queries Range Variables, Expressions and Strings Nested Queries Joins, Aggregate Operators General Constraints Grouping Triggers

3 Example Instances Sailors and Reserves relations If the key for the Reserves relation contained only the attributes sid and bid, how would the semantics differ? S1 S2 R1 sid bid day /10/ /12/96 sid sname rating age 22 dustin lubber rusty sid sname rating age 28 yuppy lubber guppy rusty

4 Basic SQL Query SQL is the standard for querying relational data Basic query structure SELECT FROM WHERE [DISTINCT] target-list relation-list qualification Relation-list: A list of relation names (possibly with a range-variable after each name) Target-list: A list of attributes of relations in relation-list

5 Basic SQL Query SQL is the standard for querying relational data Basic query structure SELECT FROM WHERE [DISTINCT] target-list relation-list qualification 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 Default is that duplicates are not eliminated!

6 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 This strategy is probably the least efficient way to compute a query! A query optimizer will find more efficient strategies to compute the same answers

7 Example of Conceptual Evaluation Query: Find names of sailors who ve reserved boat #103 Solution (Rel.Alg.): Solution (SQL): sname (( Re serves ) Sailors ) bid 103 SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103 (sid) sname rating age (sid) bid day 22 dustin /10/96 22 dustin /12/96 31 lubber /10/96 31 lubber /12/96 58 rusty /10/96 58 rusty /12/96

8 Range Variables Really needed only if the same relation appears twice in the FROM clause. The previous query can also be written as: OR SELECT sname FROM Sailors, Reserves WHERE Sailors.sid=Reserves.sid AND bid=103 SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND bid=103 Query: Find names of sailors who ve reserved boat #103 Range variables are necessary when joining a table with itself!!

9 Expressions and Strings SELECT S.age, age1=s.age-5, 2*S.age AS age2 FROM Sailors S WHERE S.sname LIKE B_%B Illustrates use of arithmetic expressions and string pattern matching: Find triples (of ages of sailors and two fields defined by expressions) for sailors whose names begin and end with B and contain at least three characters AS and = are two ways to name fields in result LIKE is used for string matching. _ stands for any one character and % stands for 0 or more arbitrary characters

10 Find sid s of sailors who ve reserved a red or a green boat UNION: Can be used to compute the union of any two union-compatible sets of tuples (which are themselves the result of SQL queries) If we replace OR by AND in the first version, what do we get? SELECT S.sid 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 ) SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color= red UNION SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color= green

11 Find sid s of sailors who ve reserved a red or a green boat EXCEPT: Used to compute the set difference of two union-compatible sets of tuples What do we get if we replace UNION by EXCEPT in the previous query? SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color= red UNION SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color= green

12 Find sid s of sailors who ve reserved a red or a green boat??? EXCEPT: Used to compute the set difference of two union-compatible sets of tuples What do we get if we replace UNION by EXCEPT in the previous query? 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 SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color= green

13 Find sid s of sailors who ve reserved a red but not a green boat EXCEPT: Used to compute the set difference of two union-compatible sets of tuples SELECT R.sid FROM Boats B, Reserves R WHERE R.bid=B.bid AND B.color= red EXCEPT SELECT R.sid FROM Boats B, Reserves R WHERE R.bid=B.bid AND B.color= green

14 Find sid s of sailors who ve reserved a red and a green boat 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. Contrast symmetry of the UNION and INTERSECT queries with how much the other versions differ SELECT S.sid FROM Sailors S, Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE S.sid=R1.sid AND R1.bid=B1.bid AND S.sid=R2.sid AND R2.bid=B2.bid AND (B1.color= red AND B2.color= green ) Key field! SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color= red INTERSECT SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color= green

15 Find sid s of sailors who ve reserved a red and a green boat BID b1 b2 B1 Colr red grn X SID s1 s1 s2 R1 BID b1 b2 b1 B1 X R1 B1 X R1 BID Colr SID BID b1 red s1 b1 b1 red s1 b2 b1 red s2 b1 b2 grn s1 b1 b2 grn s1 b2 b2 grn s2 b1

16 Find sid s of sailors who ve reserved a red and a green boat R2 B1 X R1 SID BID BID Colr SID BID s1 b1 s1 b2 s2 b1 X b1 red s1 b1 b1 red s1 b2 b1 red s2 b1 b2 grn s1 b1 b2 grn s1 b2 b2 grn s2 b1 R2 X B1 X R1 SID BID BID Colr SID BID S1 b1 b1 red s1 b1 s1 b1 b1 red s1 b2 S1 b1 b1 red s2 b1 s1 b1 b2 grn s1 b1 s1 b1 b2 grn s1 b2 s1 b1 b2 grn s2 b1 s1 b2 b1 red s1 b1 s1 b2 b1 red s1 b2 s1 b2 b1 red s2 b1 s1 b2 b2 grn s1 b1 s1 b2 b2 grn s1 b2 s1 b2 b2 grn s2 b1 s2 b1 b1 red s1 b1 s2 b1 b1 red s1 b2 s2 b1 b1 red s2 b1 s2 b1 b2 grn s1 b1 s2 b1 b2 grn s1 b2 s2 b1 b2 grn s2 b1

17 Find sid s of sailors who ve reserved a red and a green boat B2 BID Colr b1 red b2 grn X R2 X B1 X R1 SID BID BID Colr SID BID s1 b1 b1 red s1 b1 s1 b1 b1 red s1 b2 S1 b1 b1 red s2 b1 s1 b1 b2 grn s1 b1 s1 b1 b2 grn s1 b2 s1 b1 b2 grn s2 b1 s1 b2 b1 red s1 b1 s1 b2 b1 red s1 b2 s1 b2 b1 red s2 b1 s1 b2 b2 grn s1 b1 s1 b2 b2 grn s1 b2 s1 b2 b2 grn s2 b1 s2 b1 b1 red s1 b1 s2 b1 b1 red s1 b2 s2 b1 b1 red s2 b1 s2 b1 b2 grn s1 b1 s2 b1 b2 grn s1 b2 s2 b1 b2 grn s2 b1 B2 X R2 X B1 X R1 (First half) BID Colr SID BID BID Colr SID BID b1 red s1 b1 b1 red s1 b1 b1 red s1 b1 b1 red s1 b2 b1 red s1 b1 b1 red s2 b1 b1 red s1 b1 b2 grn s1 b1 b1 red s1 b1 b2 grn s1 b2 b1 red s1 b1 b2 grn s2 b1 b1 red s1 b2 b1 red s1 b1 b1 red s1 b2 b1 red s1 b2 b1 red s1 b2 b1 red s2 b1 b1 red s1 b2 b2 grn s1 b1 b1 red s1 b2 b2 grn s1 b2 b1 red s1 b2 b2 grn s2 b1 b1 red s2 b1 b1 red s1 b1 b1 red s2 b1 b1 red s1 b2 b1 red s2 b1 b1 red s2 b1 b1 red s2 b1 b2 grn s1 b1 b1 red s2 b1 b2 grn s1 b2 b1 red s2 b1 b2 grn s2 b1

18 B2 X R2 X B1 X R1 (Second half) Query: Find sid s of sailors who ve reserved a red and a green boat SELECT S.sid FROM Sailors S, Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE S.sid=R1.sid AND R1.bid=B1.bid AND S.sid=R2.sid AND R2.bid=B2.bid AND (B1.color= red AND B2.color= green ) BID Colr SID BID BID Colr SID BID b2 grn s1 b1 b1 red s1 b1 b2 grn s1 b1 b1 red s1 b2 b2 grn S1 b1 b1 red s2 b1 b2 grn s1 b1 b2 grn s1 b1 b2 grn s1 b1 b2 grn s1 b2 b2 grn s1 b1 b2 grn s2 b1 b2 grn s1 b2 b1 red s1 b1 b2 grn s1 b2 b1 red s1 b2 b2 grn s1 b2 b1 red s2 b1 b2 grn s1 b2 b2 grn s1 b1 b2 grn s1 b2 b2 grn s1 b2 b2 grn s1 b2 b2 grn s2 b1 b2 grn s2 b1 b1 red s1 b1 b2 grn s2 b1 b1 red s1 b2 b2 grn s2 b1 b1 red s2 b1 b2 grn s2 b1 b2 grn s1 b1 b2 grn s2 b1 b2 grn s1 b2 b2 grn s2 b1 b2 grn s2 b1

19 B2 X R2 X B1 X R1 (Second half) Query: Find sid s of sailors who ve reserved a red and a green boat SELECT R1.sid FROM Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE R1.sid =R2.sid AND R1.bid=B1.bid AND R2.bid=B2.bid AND (B1.color= red AND B2.color= green ) BID Colr SID BID BID Colr SID BID b2 grn s1 b1 b1 red s1 b1 b2 grn s1 b1 b1 red s1 b2 b2 grn S1 b1 b1 red s2 b1 b2 grn s1 b1 b2 grn s1 b1 b2 grn s1 b1 b2 grn s1 b2 b2 grn s1 b1 b2 grn s2 b1 b2 grn s1 b2 b1 red s1 b1 b2 grn s1 b2 b1 red s1 b2 b2 grn s1 b2 b1 red s2 b1 b2 grn s1 b2 b2 grn s1 b1 b2 grn s1 b2 b2 grn s1 b2 b2 grn s1 b2 b2 grn s2 b1 b2 grn s2 b1 b1 red s1 b1 b2 grn s2 b1 b1 red s1 b2 b2 grn s2 b1 b1 red s2 b1 b2 grn s2 b1 b2 grn s1 b1 b2 grn s2 b1 b2 grn s1 b2 b2 grn s2 b1 b2 grn s2 b1

20 B2 X R2 X B1 X R1 (Second half) Query: Find sid s of sailors who ve reserved a red and a green boat SELECT R1.sid FROM Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE R1.sid =R2.sid AND R1.bid=B1.bid AND R2.bid=B2.bid AND (B1.color= red AND B2.color= green ) BID Colr SID BID BID Colr SID BID b2 grn s1 b1 b1 red s1 b1 b2 grn s1 b1 b1 red s1 b2 b2 grn S1 b1 b1 red s2 b1 b2 grn s1 b1 b2 grn s1 b1 b2 grn s1 b1 b2 grn s1 b2 b2 grn s1 b1 b2 grn s2 b1 b2 grn s1 b2 b1 red s1 b1 b2 grn s1 b2 b1 red s1 b2 b2 grn s1 b2 b1 red s2 b1 b2 grn s1 b2 b2 grn s1 b1 b2 grn s1 b2 b2 grn s1 b2 b2 grn s1 b2 b2 grn s2 b1 b2 grn s2 b1 b1 red s1 b1 b2 grn s2 b1 b1 red s1 b2 b2 grn s2 b1 b1 red s2 b1 b2 grn s2 b1 b2 grn s1 b1 b2 grn s2 b1 b2 grn s1 b2 b2 grn s2 b1 b2 grn s2 b1

21 B2 X R2 X B1 X R1 (Second half) Query: Find sid s of sailors who ve reserved a red and a green boat SELECT R1.sid FROM Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE R1.sid =R2.sid AND R1.bid=B1.bid AND R2.bid=B2.bid AND (B1.color= red AND B2.color= green ) BID Colr SID BID BID Colr SID BID b2 grn s1 b1 b1 red s1 b1 b2 grn s1 b1 b1 red s1 b2 b2 grn S1 b1 b1 red s2 b1 b2 grn s1 b2 b1 red s1 b1 b2 grn s1 b2 b1 red s1 b2 b2 grn s1 b2 b1 red s2 b1 b2 grn s2 b1 b1 red s1 b1 b2 grn s2 b1 b1 red s1 b2 b2 grn s2 b1 b1 red s2 b1

22 B2 X R2 X B1 X R1 (Second half) Query: Find sid s of sailors who ve reserved a red and a green boat SELECT R1.sid FROM Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE R1.sid =R2.sid AND R1.bid=B1.bid AND R2.bid=B2.bid AND (B1.color= red AND B2.color= green ) BID Colr SID BID BID Colr SID BID b2 grn s1 b1 b1 red s1 b1 b2 grn s1 b1 b1 red s1 b2 b2 grn S1 b1 b1 red s2 b1 b2 grn s1 b2 b1 red s1 b1 b2 grn s1 b2 b1 red s1 b2 b2 grn s1 b2 b1 red s2 b1 b2 grn s2 b1 b1 red s1 b1 b2 grn s2 b1 b1 red s1 b2 b2 grn s2 b1 b1 red s2 b1

23 B2 X R2 X B1 X R1 (Second half) Query: Find sid s of sailors who ve reserved a red and a green boat SELECT R1.sid FROM Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE R1.sid =R2.sid AND R1.bid=B1.bid AND R2.bid=B2.bid AND (B1.color= red AND B2.color= green ) BID Colr SID BID BID Colr SID BID b2 grn s1 b2 b1 red s1 b1 b2 grn s1 b2 b1 red s1 b2 b2 grn s1 b2 b1 red s2 b1

24 B2 X R2 X B1 X R1 (Second half) Query: Find sid s of sailors who ve reserved a red and a green boat SELECT R1.sid FROM Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE R1.sid =R2.sid AND R1.bid=B1.bid AND R2.bid=B2.bid AND (B1.color= red AND B2.color= green ) BID Colr SID BID BID Colr SID BID b2 grn s1 b2 b1 red s1 b1 b2 grn s1 b2 b1 red s1 b2 b2 grn s1 b2 b1 red s2 b1

25 B2 X R2 X B1 X R1 (Second half) Query: Find sid s of sailors who ve reserved a red and a green boat SELECT R1.sid FROM Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE R1.sid =R2.sid AND R1.bid=B1.bid AND R2.bid=B2.bid AND (B1.color= red AND B2.color= green ) BID Colr SID BID BID Colr SID BID b2 grn s1 b2 b1 red s1 b1 b2 grn s1 b2 b1 red s2 b1

26 B2 X R2 X B1 X R1 (Second half) Query: Find sid s of sailors who ve reserved a red and a green boat SELECT R1.sid FROM Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE R1.sid =R2.sid AND R1.bid=B1.bid AND R2.bid=B2.bid AND (B1.color= red AND B2.color= green ) BID Colr SID BID BID Colr SID BID b2 grn s1 b2 b1 red s1 b1 b2 grn s1 b2 b1 red s2 b1

27 B2 X R2 X B1 X R1 (Second half) Query: Find sid s of sailors who ve reserved a red and a green boat BID Colr SID BID BID Colr SID BID SELECT R1.sid FROM Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE R1.sid =R2.sid AND R1.bid=B1.bid AND R2.bid=B2.bid AND (B1.color= red AND B2.color= green ) b2 grn s1 b2 b1 red s1 b1

28 Nested Queries SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid=103) A very powerful feature of SQL: a WHERE clause can itself contain an SQL query! (Actually, so can FROM and HAVING clauses) To understand semantics of nested queries, think of a nested loops evaluation: For each Sailors tuple, check the qualification by computing the subquery For (i=1 10) do { x=x+1; For (j=1 5) do { y=y+1; } } Find names of sailors who ve reserved boat #103:

29 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)

30 Nested Queries Find names of sailors who ve NOT reserved boat #103: SELECT S.sname FROM Sailors S WHERE S.sid NOT IN (SELECT R.sid FROM Reserves R WHERE R.bid=103)

31 Nested Queries with Correlation Find names of sailors who ve reserved boat #103: SELECT S.sname FROM Sailors S WHERE EXISTS (SELECT * FROM Reserves R WHERE R.bid=103 AND S.sid = R.sid) EXISTS is another set comparison operator, like IN

32 Nested Queries with Correlation Find names of sailors with at most one reservation for boat #103: SELECT S.sname FROM Sailors S WHERE UNIQUE (SELECT R.sid FROM Reserves R WHERE R.bid=103 AND S.sid = R.sid) If UNIQUE is used, and * is replaced by R.bid UNIQUE checks for duplicate tuples; returns true if no row appears twice UNIQUE returns true if the answer is empty * denotes all attributes; Why do we have to replace * by R.bid? Illustrates why, in general, subquery must be re-computed for each Sailors tuple

33 More on Set-Comparison Operators We ve already seen IN, EXISTS and UNIQUE. Can also use negated versions: NOT IN, NOT EXISTS and NOT UNIQUE Also available: op ANY, op ALL, op IN {,,, ( ), ( ), ( )} 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 )

34 Rewriting INTERSECT Queries Using IN Find sid s of sailors who ve reserved both a red and a green boat: SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color= red AND S.sid IN (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, EXCEPT queries re-written using NOT IN To find names (not sid s) of Sailors who ve reserved both red and green boats, just replace S.sid by S.sname in SELECT clause. (What about INTERSECT query?)

35 Rewriting INTERSECT Queries Using IN Find sid s of sailors who ve reserved both a red and a green boat: To find names (not sid s) of Sailors who ve reserved both red and green boats, just replace S.sid by S.sname in SELECT clause. (What about INTERSECT query?) SELECT S.sname FROM Sailors S WHERE S.sid IN (( SELECT R.sid FROM Boats B, Reserves R WHERE R.bid=B.bid AND B.color= red ) INTERSECT (SELECT R.sid FROM Boats B2, Reserves R2 WHERE R2.bid=B2.bid AND B2.color= green )

36 Division in SQL Find sailors who ve reserved all boats How to do it the hard way, without EXCEPT? SELECT S.sname FROM Sailors S WHERE NOT EXISTS (SELECT B.bid FROM Boats B Sailors S such that... there is no boat B without... SELECT S.sname FROM Sailors S WHERE NOT EXISTS ((SELECT B.bid FROM Boats B) EXCEPT (SELECT R.bid FROM Reserves R WHERE R.sid=S.sid)) WHERE NOT EXISTS (SELECT R.bid FROM Reserves R a Reserves tuple showing S reserved B WHERE R.bid=B.bid AND R.sid=S.sid))

37 Joins (SQL 2003 std, source: wikipedia) Department Table DepartmentID DepartmentName 31 Sales 33 Engineering 34 Clerical 35 Marketing Employee Table LastName DepartmentID Rafferty 31 Jones 33 Steinberg 33 Robinson 34 Smith 34 Jasper 36 Adapted from the slides of Yücel Saygın

38 Inner Joins SELECT * FROM employee INNER JOIN department ON employee.departmentid = department.departmentid SELECT * FROM employee, department WHERE employee.departmentid = department.departmentid

39 Inner Joins Employee.LastName Employee.DepartmentID Department.DepartmentName Department.DepartmentID Smith 34 Clerical 34 Jones 33 Engineering 33 Robinson 34 Clerical 34 Steinberg 33 Engineering 33 Rafferty 31 Sales 31

40 Joins SELECT * FROM employee NATURAL JOIN department Employee.LastName DepartmentID Department.DepartmentName Smith 34 Clerical Jones 33 Engineering Robinson 34 Clerical Steinberg 33 Engineering Rafferty 31 Sales SELECT * FROM employee CROSS JOIN department SELECT * FROM employee, department;

41 Employee. LastName Joins (Outer Joins) SELECT * FROM employee LEFT OUTER JOIN department ON department.departmentid = employee.departmentid Employee. DepartmentID Department. DepartmentName Jones 33 Engineering 33 Rafferty 31 Sales 31 Robinson 34 Clerical 34 Smith 34 Clerical 34 Jasper 36 NULL NULL Steinberg 33 Engineering 33 Department. DepartmentID

42 Joins (Full Outer Join) SELECT * FROM employee FULL OUTER JOIN department ON department.departmentid = employee.departmentid Some DBMSs do not support FULL OUTER JOIN! Can you implement FULL OUTER JOIN WITH LEFT and RIGHT OUTER JOINS?

43 Aggregate Operators Significant extension of relational algebra A function where the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning or measurement such as a set, a bag or a list COUNT (*) COUNT ( [DISTINCT] A) SUM ( [DISTINCT] A) AVG ( [DISTINCT] A) MAX (A) MIN (A) single column Used to write statistical queries Mainly used for reporting such as Total sales in 2014 Average, max, min income of employees Total number of employees hired in

44 Aggregate Operators COUNT (*): The number of values in a table 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

45 Aggregate Operators Except for COUNT, aggregate functions ignore null values Aggregate functions are frequently used with the GROUP BY clause of the SELECT statement Total number of Sailors? SELECT COUNT (*) FROM Sailors S COUNT (*) COUNT ( [DISTINCT] A) SUM ( [DISTINCT] A) AVG ( [DISTINCT] A) MAX (A) MIN (A) single column Average age of Sailors whose ratings are 10 SELECT AVG (S.age) FROM Sailors S WHERE S.rating=10 Average distinct age of Sailors whose ratings are 10 SELECT AVG ( DISTINCT S.age) FROM Sailors S WHERE S.rating=10

46 Aggregate Operators Name of Sailors whose ratings are equal to the maximum rating among Sailors SELECT S.sname FROM Sailors S WHERE S.rating= (SELECT MAX(S2.rating) FROM Sailors S2) Number of distinct ratings in Sailors whose names are Bob SELECT COUNT (DISTINCT S.rating) FROM Sailors S WHERE S.sname= Bob COUNT (*) COUNT ( [DISTINCT] A) SUM ( [DISTINCT] A) AVG ( [DISTINCT] A) MAX (A) MIN (A) SELECT COUNT (S.rating) FROM Sailors S single column How many different ratings are there among the Sailors?? SELECT COUNT (DISTINCT S.rating) FROM Sailors S

47 Find name and age of the oldest sailor(s) SELECT S.sname, MAX(S.age) FROM Sailors S? This query is illegal! If the Select clause uses an aggregate operation, then it must use only aggregate operations unless the query contains a GROUP BY clause SELECT S.sname, S.age FROM Sailors S WHERE (SELECT MAX (S2.age) FROM Sailors S2) = S.age This query is allowed in the SQL/92 standard, but is not supported in some systems

48 Find name and age of the oldest sailor(s) SELECT S.sname, S.age FROM Sailors S WHERE (SELECT MAX (S2.age) FROM Sailors S2) = S.age SELECT S.sname, S.age FROM Sailors S WHERE S.age = (SELECT MAX (S2.age) FROM Sailors S2) This query is allowed in the SQL/92 standard, but is not supported in some systems This query is allowed in the SQL/92 standard and is valid for all systems SELECT S.sname, S.age FROM Sailors S WHERE S.age > ALL (SELECT S2.age FROM Sailors S2)

49 Motivation for Grouping We ve applied aggregate operators to all (qualifying) tuples Sometimes, we want to apply them to each of several groups of tuples Find the age of the youngest sailor for each rating level In general, we don t know how many rating levels exist, and what the rating values for these levels are Suppose we know that rating values go from 1 to 10; we can write 10 queries that look like this: For i = 1, 2,..., 10: SELECT MIN (S.age) FROM Sailors S WHERE S.rating = i

50 Queries with GROUP BY and HAVING SELECT [DISTINCT] target-list FROM relation-list WHERE qualification GROUP BY grouping-list HAVING group-qualification The target-list contains i. attribute names ii. terms with aggregate operations (e.g., MIN (S.age)) The attribute list (i) must be a subset of grouping-list Each answer tuple corresponds to a group, and these attributes must have a single value per group A group is a set of tuples that have the same value for all attributes in grouping-list

51 Conceptual Evaluation The cross-product of relation-list is computed, tuples that fail qualification are discarded, `unnecessary fields are deleted, and 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 Expressions in group-qualification must have a single value per group In effect, an attribute in group-qualification that is not an argument of an aggregate op also appears in grouping-list One answer tuple is generated per qualifying group

52 SELECT target-list FROM relation-list WHERE qualification Conceptual Evaluation SELECT [DISTINCT] target-list FROM relation-list WHERE qualification GROUP BY grouping-list HAVING group-qualification GROUP BY grouping-list HAVING group-qualification gr1 gr2 RESULT gr3 gr4

53 SELECT S.rating FROM Sailors S WHERE S.age >= 18 Age = 20 Age = 25 Age = 19 Age=70 Age = 60 Age = 40 Age = 33 Age = 32 Age = 18 Age = 22 Age = 39 Conceptual Evaluation GROUP BY S.rating HAVING COUNT(*) > 1 Rating = 4 Rating =2 Rating =3 Rating=2 Rating=3 Rating=5 Rating=1 Rating=4 Rating=3 Rating=4 Rating=1 gr1 gr2 gr3 gr4 Rating=1 Rating=1 Rating=2 Rating=2 Rating=3 Rating=3 Rating=3 Rating=4 Rating=4 Rating=4 Rating=5 SELECT S.rating FROM Sailors S WHERE S.age >= 18 GROUP BY S.rating HAVING COUNT (*) > 1 RESULT Rating = 1 Rating = 2 Rating = 3 Rating = 4

54 Find age of the youngest sailor with age 18, for each rating with at least 2 such sailors SELECT S.rating, MIN (S.age) AS minage FROM Sailors S WHERE S.age >= 18 GROUP BY S.rating HAVING COUNT (*) > 1 Only S.rating and S.age are mentioned in the SELECT, GROUP BY or HAVING clauses; 2nd column of result is named minage using AS rating minage Answer relation: Sailors instance: sid sname rating age 22 dustin brutus lubber andy rusty horatio zorba horatio art bob frodo

55 Find age of the youngest sailor with age 18, for each rating with at least 2 such sailors rating age rating age rating minage

56 Find age of the youngest sailor with age > 18, for each rating with at least 2 sailors (of any age) 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) Shows HAVING clause can also contain a subquery. Compare this with the query where we considered only ratings with 2 sailors over 18! What if HAVING clause is replaced by: HAVING COUNT(*) >1 Sailors instance: sid sname rating age 22 dustin brutus lubber andy rusty horatio zorba horatio art bob frodo

57 Find age of the youngest sailor with age > 18, for each rating with at least 2 sailors (of any age) SELECT S.rating, MIN (S.age) AS minage FROM Sailors S WHERE S.age > 18 GROUP BY S.rating HAVING 1 < (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating=S2.rating) Answer relation: rating minage Sailors instance: sid sname rating age 22 dustin brutus lubber andy rusty horatio zorba horatio art bob frodo

58 Find age of the youngest sailor with age > 18, for each rating with at least 2 sailors (of any age) Shows HAVING clause can also contain a subquery. Compare this with the query where we considered only ratings with 2 sailors over 18! What if HAVING clause is replaced by: HAVING COUNT(*) >1 SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age > 18 GROUP BY S.rating HAVING COUNT (*) > 1 Sailors instance: sid sname rating age 22 dustin brutus lubber andy rusty horatio zorba horatio art bob frodo

59 Find age of the youngest sailor with age > 18, for each rating with at least 2 sailors (of any age) SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age > 18 GROUP BY S.rating HAVING COUNT (*) > 1 Answer relation: rating minage Sailors instance: sid sname rating age 22 dustin brutus lubber andy rusty horatio zorba horatio art bob frodo

60 Find those ratings for which the average age is the minimum over all ratings Aggregate operations cannot be nested! WRONG: SELECT S.rating FROM Sailors S WHERE S.age = (SELECT MIN (AVG (S2.age)) FROM Sailors S2) Correct solution (in SQL/92): 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 (Temp2.avgage) FROM (SELECT AVG (S.age) AS avgage FROM _Sailors S GROUP BY S.rating) AS Temp2)

61 For each red boat, find the number of reservations for this boat

62 For each red boat, find the number of reservations for this boat SELECT B.bid, COUNT (*) AS scount FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color= red GROUP BY B.bid Grouping over a join of three relations. What do we get if we remove B.color= red from the WHERE clause and add a HAVING clause with this condition? SELECT B.bid, COUNT (*) AS scount FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid GROUP BY B.bid HAVING B.color= red

63 Find the product models for which the maximum list price is more than twice the average for the model USE AdventureWorks2008R2; GO SELECT p1.productmodelid FROM Production.Product p1 GROUP BY p1.productmodelid HAVING MAX(p1.ListPrice) >= ALL (SELECT 2 * AVG(p2.ListPrice) FROM Production.Product p2 WHERE p1.productmodelid = p2.productmodelid) ; GO

64 Null Values Field values in a tuple are sometimes unknown (e.g., a rating has not been assigned) or inapplicable (e.g., no maiden name) SQL provides a special value null for such situations The presence of null complicates many issues Special operators needed to check if value is/is not null Is rating>8 true or false when rating is equal to null? What about AND, OR and NOT connectives? We need a 3-valued logic (true, false and unknown) Meaning of constructs must be defined carefully WHERE clause eliminates rows that don t evaluate to true New operators (in particular, outer joins) possible/needed

65 Integrity Constraints 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 Can be used to 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

66 General Constraints Useful when more general ICs than keys are involved Can use queries to express constraint Constraints can be named CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( rating >= 1 AND rating <= 10 ) 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)))

67 Constraints Over Multiple Relations CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK Number of boats plus number of sailors is < 100 ( (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 Awkward and wrong! If Sailors is empty, the number of Boats tuples can be anything! CREATE ASSERTION smallclub CHECK ( (SELECT COUNT (S.sid) FROM Sailors S) + (SELECT COUNT (B.bid) FROM Boats B) < 100 )

68 Triggers Trigger: procedure that starts automatically if specified changes occur to the DBMS Deamon that monitors a database, and is executed when the DB is modified in a way that matches the event specification An insert, delete or update statement could activate a trigger (before/after executing the changes) Three parts: Event (activates the trigger) Condition (tests whether the triggers should run) Action (what happens if the trigger runs)

69 Triggers: Example (SQL:1999) 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 <= 18

70 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 RA 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

71 Summary NULL for unknown field values brings many complications SQL allows specification of rich integrity constraints Triggers respond to changes in the database

72 Sample Questions

73 Q11: List the names of managers with at least one dependent EMPLOYEE(NAME, SSN, BDATE, ADDRESS, SALARY, SUPERSSN, DNO) DEPARTMENT(DNAME, DNUMBER, MGRSSN, MGRSTARTDATE) DEPT_LOCATIONS(DNUMBER, DLOCATION) PROJECT(PNAME, PNUMBER, PLOCATION, DNUM) WORKSON(ESSN, PNO, HOURS) DEPENDENT(ESSN, DEPENDENT_NAME, SEX, BDATE, RELATIONSHIP) SELECT FROM WHERE EMPLOYEE.NAME EMPLOYEE, DEPARTMENT DEPARTMENT.MGRSSN = EMPLOYEE.SSN AND EMPLOYEE.SSN IN (SELECT DISTINCT ESSN FROM DEPENDENT)

74 Q12: List the names of employees who do not work on a project controlled by department no 5 EMPLOYEE(NAME, SSN, BDATE, ADDRESS, SALARY, SUPERSSN, DNO) DEPARTMENT(DNAME, DNUMBER, MGRSSN, MGRSTARTDATE) DEPT_LOCATIONS(DNUMBER, DLOCATION) PROJECT(PNAME, PNUMBER, PLOCATION, DNUM) WORKSON(ESSN, PNO, HOURS) DEPENDENT(ESSN, DEPENDENT_NAME, SEX, BDATE, RELATIONSHIP) SELECT NAME FROM EMPLOYEE WHERE SSN NOT IN (SELECT WORKSON.ESSN FROM WORKSON, PROJECT WHERE WORKSON.PNO = PROJECT.PNUMBER AND PROJECT.DNUM = 5)

75 Q13: List the names of employees who do not work on all projects controlled by department no 5 EMPLOYEE(NAME, SSN, BDATE, ADDRESS, SALARY, SUPERSSN, DNO) DEPARTMENT(DNAME, DNUMBER, MGRSSN, MGRSTARTDATE) DEPT_LOCATIONS(DNUMBER, DLOCATION) PROJECT(PNAME, PNUMBER, PLOCATION, DNUM) WORKSON(ESSN, PNO, HOURS) DEPENDENT(ESSN, DEPENDENT_NAME, SEX, BDATE, RELATIONSHIP) SELECT E.NAME FROM WORKSON W, EMPLOYEE E WHERE E.SSN = W.ESSN AND EXISTS ((SELECT P.PNUMBER FROM PROJECT P WHERE P.DNUM = 5) EXCEPT (SELECT W1.PNO FROM WORKSON W1 WHERE W1.ESSN = W.ESSN)) ORACLE DOES NOT SUPPORT EXCEPT!!! SQL Server Supports it

76 Q13: List the names of employees who do not work on all projects controlled by department no 5 EMPLOYEE(NAME, SSN, BDATE, ADDRESS, SALARY, SUPERSSN, DNO) DEPARTMENT(DNAME, DNUMBER, MGRSSN, MGRSTARTDATE) DEPT_LOCATIONS(DNUMBER, DLOCATION) PROJECT(PNAME, PNUMBER, PLOCATION, DNUM) WORKSON(ESSN, PNO, HOURS) DEPENDENT(ESSN, DEPENDENT_NAME, SEX, BDATE, RELATIONSHIP) SELECT E.NAME FROM WORKSON W, EMPLOYEE E WHERE E.SSN = W.ESSN AND EXISTS (SELECT P.PNUMBER FROM PROJECT P WHERE P.DNUM = 5 AND NOT EXISTS (SELECT W1.ESSN FROM WORKSON W1 WHERE W1.ESSN = W.ESSN AND W1.PNO = P.PNUMBER))

77 Q14: List the names of employees who do not have supervisors (IS NULL checks for null values!) EMPLOYEE(NAME, SSN, BDATE, ADDRESS, SALARY, SUPERSSN, DNO) DEPARTMENT(DNAME, DNUMBER, MGRSSN, MGRSTARTDATE) DEPT_LOCATIONS(DNUMBER, DLOCATION) PROJECT(PNAME, PNUMBER, PLOCATION, DNUM) WORKSON(ESSN, PNO, HOURS) DEPENDENT(ESSN, DEPENDENT_NAME, SEX, BDATE, RELATIONSHIP) SELECT NAME FROM EMPLOYEE WHERE SUPERSSN IS NULL

78 Q15: Find the SUM of the salaries of all employees, the max salary, min salary and average salary EMPLOYEE(NAME, SSN, BDATE, ADDRESS, SALARY, SUPERSSN, DNO) DEPARTMENT(DNAME, DNUMBER, MGRSSN, MGRSTARTDATE) DEPT_LOCATIONS(DNUMBER, DLOCATION) PROJECT(PNAME, PNUMBER, PLOCATION, DNUM) WORKSON(ESSN, PNO, HOURS) DEPENDENT(ESSN, DEPENDENT_NAME, SEX, BDATE, RELATIONSHIP) SELECT SUM(SALARY) AS SALARY_SUM, MAX(SALARY) AS MAX_SALARY, MIN(SALARY) AS MIN_SALARY, AVG(SALARY) AS AVERAGE_SALARY FROM EMPLOYEE

79 Q16: Find the SUM of the salaries of all employees, the max salary, min salary and average salary for research department EMPLOYEE(NAME, SSN, BDATE, ADDRESS, SALARY, SUPERSSN, DNO) DEPARTMENT(DNAME, DNUMBER, MGRSSN, MGRSTARTDATE) DEPT_LOCATIONS(DNUMBER, DLOCATION) PROJECT(PNAME, PNUMBER, PLOCATION, DNUM) WORKSON(ESSN, PNO, HOURS) DEPENDENT(ESSN, DEPENDENT_NAME, SEX, BDATE, RELATIONSHIP) SELECT SUM(SALARY) AS SALARY_SUM, MAX(SALARY) AS MAX_SALARY, MIN(SALARY) AS MIN_SALARY, AVG(SALARY) AS AVERAGE_SALARY FROM EMPLOYEE, DEPARTMENT WHERE EMPLOYEE.DNO = DEPARTMENT.DNUMBER AND DEPARTMENT.DNAME = 'RESEARCH'

80 Q17: Find the number of employees in research department EMPLOYEE(NAME, SSN, BDATE, ADDRESS, SALARY, SUPERSSN, DNO) DEPARTMENT(DNAME, DNUMBER, MGRSSN, MGRSTARTDATE) DEPT_LOCATIONS(DNUMBER, DLOCATION) PROJECT(PNAME, PNUMBER, PLOCATION, DNUM) WORKSON(ESSN, PNO, HOURS) DEPENDENT(ESSN, DEPENDENT_NAME, SEX, BDATE, RELATIONSHIP) SELECT COUNT(*) AS EMPLOYEE_COUNT FROM EMPLOYEE, DEPARTMENT WHERE EMPLOYEE.DNO = DEPARTMENT.DNUMBER AND DEPARTMENT.DNAME = 'RESEARCH'

81 Q19: Display the names of the employees who do not practice birth control (more than 5 children) EMPLOYEE(NAME, SSN, BDATE, ADDRESS, SALARY, SUPERSSN, DNO) DEPARTMENT(DNAME, DNUMBER, MGRSSN, MGRSTARTDATE) DEPT_LOCATIONS(DNUMBER, DLOCATION) PROJECT(PNAME, PNUMBER, PLOCATION, DNUM) WORKSON(ESSN, PNO, HOURS) DEPENDENT(ESSN, DEPENDENT_NAME, SEX, BDATE, RELATIONSHIP) SELECT NAME FROM EMPLOYEE WHERE SSN IN (SELECT ESSN FROM DEPENDENT WHERE RELATIONSHIP = 'Child' GROUP BY ESSN HAVING COUNT(*) > 5)

82 Q20: For each department, retrieve the department number, number of employees in that department and the average salary EMPLOYEE(NAME, SSN, BDATE, ADDRESS, SALARY, SUPERSSN, DNO) DEPARTMENT(DNAME, DNUMBER, MGRSSN, MGRSTARTDATE) DEPT_LOCATIONS(DNUMBER, DLOCATION) PROJECT(PNAME, PNUMBER, PLOCATION, DNUM) WORKSON(ESSN, PNO, HOURS) DEPENDENT(ESSN, DEPENDENT_NAME, SEX, BDATE, RELATIONSHIP) SELECT DNO, COUNT(*) AS EMPLOYEE_COUNT, AVG(SALARY) AS AVERAGE_SALARY FROM EMPLOYEE GROUP BY DNO

83 Q21: For each project, retrieve the project number, the project name, and the number of employees who work for that project EMPLOYEE(NAME, SSN, BDATE, ADDRESS, SALARY, SUPERSSN, DNO) DEPARTMENT(DNAME, DNUMBER, MGRSSN, MGRSTARTDATE) DEPT_LOCATIONS(DNUMBER, DLOCATION) PROJECT(PNAME, PNUMBER, PLOCATION, DNUM) WORKSON(ESSN, PNO, HOURS) DEPENDENT(ESSN, DEPENDENT_NAME, SEX, BDATE, RELATIONSHIP) SELECT PROJECT.PNAME, PROJECT.PNUMBER, COUNT(*) AS EMPLOYEE_COUNT FROM PROJECT, WORKSON WHERE WORKSON.PNO = PROJECT.PNUMBER GROUP BY PROJECT.PNUMBER DO YOU SEE ANYTHING WRONG WITH THIS QUERY?

84 Q22: For each project on which more than two employees work, retrieve the project number, the project name, and the number of employees who work on the project EMPLOYEE(NAME, SSN, BDATE, ADDRESS, SALARY, SUPERSSN, DNO) DEPARTMENT(DNAME, DNUMBER, MGRSSN, MGRSTARTDATE) DEPT_LOCATIONS(DNUMBER, DLOCATION) PROJECT(PNAME, PNUMBER, PLOCATION, DNUM) WORKSON(ESSN, PNO, HOURS) DEPENDENT(ESSN, DEPENDENT_NAME, SEX, BDATE, RELATIONSHIP) SELECT PROJECT.PNAME, PROJECT.PNUMBER, COUNT(*) AS EMPLOYEE_COUNT FROM PROJECT, WORKSON WHERE WORKSON.PNO = PROJECT.PNUMBER GROUP BY PROJECT.PNUMBER, PROJECT.PNAME HAVING COUNT(*) > 2

85 Q23: For each department that has more than five employees, retrieve the department number and the number of its employees who are making more than yearly EMPLOYEE(NAME, SSN, BDATE, ADDRESS, SALARY, SUPERSSN, DNO) DEPARTMENT(DNAME, DNUMBER, MGRSSN, MGRSTARTDATE) DEPT_LOCATIONS(DNUMBER, DLOCATION) PROJECT(PNAME, PNUMBER, PLOCATION, DNUM) WORKSON(ESSN, PNO, HOURS) DEPENDENT(ESSN, DEPENDENT_NAME, SEX, BDATE, RELATIONSHIP) SELECT DNO, COUNT(*) AS EMPLOYEE_COUNT FROM EMPLOYEE WHERE SALARY * 12 > AND DNO IN (SELECT DNO FROM EMPLOYEE GROUP BY DNO HAVING COUNT(*) > 5) GROUP BY DNO

SQL: Queries, Programming, Triggers

SQL: Queries, Programming, Triggers SQL: Queries, Programming, Triggers Chapter 5 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1 R1 Example Instances We will use these instances of the Sailors and Reserves relations in

More information

Example Instances. SQL: Queries, Programming, Triggers. Conceptual Evaluation Strategy. Basic SQL Query. A Note on Range Variables

Example Instances. SQL: Queries, Programming, Triggers. Conceptual Evaluation Strategy. Basic SQL Query. A Note on Range Variables SQL: Queries, Programming, Triggers Chapter 5 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1 Example Instances We will use these instances of the Sailors and Reserves relations in our

More information

SQL: Queries, Programming, Triggers

SQL: Queries, Programming, Triggers SQL: Queries, Programming, Triggers CSC343 Introduction to Databases - A. Vaisman 1 R1 Example Instances We will use these instances of the Sailors and Reserves relations in our examples. If the key for

More information

Chapter 5. SQL: Queries, Constraints, Triggers

Chapter 5. SQL: Queries, Constraints, Triggers Chapter 5 SQL: Queries, Constraints, Triggers 1 Overview: aspects of SQL DML: Data Management Language. Pose queries (Ch. 5) and insert, delete, modify rows (Ch. 3) DDL: Data Definition Language. Creation,

More information

Relational Algebra and SQL

Relational Algebra and SQL Relational Algebra and SQL Johannes Gehrke johannes@cs.cornell.edu http://www.cs.cornell.edu/johannes Slides from Database Management Systems, 3 rd Edition, Ramakrishnan and Gehrke. Database Management

More information

Boats bid bname color 101 Interlake blue 102 Interlake red 103 Clipper green 104 Marine red. Figure 1: Instances of Sailors, Boats and Reserves

Boats bid bname color 101 Interlake blue 102 Interlake red 103 Clipper green 104 Marine red. Figure 1: Instances of Sailors, Boats and Reserves 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:

More information

Part A: Data Definition Language (DDL) Schema and Catalog CREAT TABLE. Referential Triggered Actions. CSC 742 Database Management Systems

Part A: Data Definition Language (DDL) Schema and Catalog CREAT TABLE. Referential Triggered Actions. CSC 742 Database Management Systems CSC 74 Database Management Systems Topic #0: SQL Part A: Data Definition Language (DDL) Spring 00 CSC 74: DBMS by Dr. Peng Ning Spring 00 CSC 74: DBMS by Dr. Peng Ning Schema and Catalog Schema A collection

More information

CSC 443 Data Base Management Systems. Basic SQL

CSC 443 Data Base Management Systems. Basic SQL CSC 443 Data Base Management Systems Lecture 6 SQL As A Data Definition Language Basic SQL SQL language Considered one of the major reasons for the commercial success of relational databases SQL Structured

More information

Θεµελίωση Βάσεων εδοµένων

Θεµελίωση Βάσεων εδοµένων Θεµελίωση Βάσεων εδοµένων Βασίλης Βασσάλος 1 What do we need to produce good software? Good programmers, software engineers, project managers, business experts, etc. (People) Good software development

More information

The SQL Query Language. Creating Relations in SQL. Referential Integrity in SQL. Basic SQL Query. Primary and Candidate Keys in SQL

The SQL Query Language. Creating Relations in SQL. Referential Integrity in SQL. Basic SQL Query. Primary and Candidate Keys in SQL COS 597A: Principles of Database and Information Systems SQL: Overview and highlights The SQL Query Language Structured Query Language Developed by IBM (system R) in the 1970s Need for a standard since

More information

Introduction to SQL: Data Retrieving

Introduction to SQL: Data Retrieving Introduction to SQL: Data Retrieving Ruslan Fomkin Databasdesign för Ingenjörer 1056F Structured Query Language (SQL) History: SEQUEL (Structured English QUery Language), earlier 70 s, IBM Research SQL

More information

Part 4: Database Language - SQL

Part 4: Database Language - SQL Part 4: Database Language - SQL Junping Sun Database Systems 4-1 Database Languages and Implementation Data Model Data Model = Data Schema + Database Operations + Constraints Database Languages such as

More information

COMP 5138 Relational Database Management Systems. Week 5 : Basic SQL. Today s Agenda. Overview. Basic SQL Queries. Joins Queries

COMP 5138 Relational Database Management Systems. Week 5 : Basic SQL. Today s Agenda. Overview. Basic SQL Queries. Joins Queries COMP 5138 Relational Database Management Systems Week 5 : Basic COMP5138 "Relational Database Managment Systems" J. Davis 2006 5-1 Today s Agenda Overview Basic Queries Joins Queries Aggregate Functions

More information

Chapter 8. SQL-99: SchemaDefinition, Constraints, and Queries and Views

Chapter 8. SQL-99: SchemaDefinition, Constraints, and Queries and Views Chapter 8 SQL-99: SchemaDefinition, Constraints, and Queries and Views Data Definition, Constraints, and Schema Changes Used to CREATE, DROP, and ALTER the descriptions of the tables (relations) of a database

More information

UNIT 6. Structured Query Language (SQL) Text: Chapter 5

UNIT 6. Structured Query Language (SQL) Text: Chapter 5 UNIT 6 Structured Query Language (SQL) Text: Chapter 5 Learning Goals Given a database (a set of tables ) you will be able to express a query in SQL, involving set operators, subqueries and aggregations

More information

Relational Schema. CS 4700/6700 A Sample of Small Database Design Using Microsoft Access

Relational Schema. CS 4700/6700 A Sample of Small Database Design Using Microsoft Access CS 4700/6700 A Sample of Small Database Design Using Microsoft Access Company relational database schema from the textbook (Fundamentals of Database systems, 6 th Edition, by Ramez Elmasri and Shamkant

More information

Relational Algebra. Module 3, Lecture 1. Database Management Systems, R. Ramakrishnan 1

Relational Algebra. Module 3, Lecture 1. Database Management Systems, R. Ramakrishnan 1 Relational Algebra Module 3, Lecture 1 Database Management Systems, R. Ramakrishnan 1 Relational Query Languages Query languages: Allow manipulation and retrieval of data from a database. Relational model

More information

SQL Nested & Complex Queries. CS 377: Database Systems

SQL Nested & Complex Queries. CS 377: Database Systems SQL Nested & Complex Queries CS 377: Database Systems Recap: Basic SQL Retrieval Query A SQL query can consist of several clauses, but only SELECT and FROM are mandatory SELECT FROM

More information

SQL-99: Schema Definition, Basic Constraints, and Queries

SQL-99: Schema Definition, Basic Constraints, and Queries 8 SQL-99: Schema Definition, Basic Constraints, and Queries The SQL language may be considered one of the major reasons for the success of relational databases in the commercial world. Because it became

More information

How To Create A Table In Sql 2.5.2.2 (Ahem)

How To Create A Table In Sql 2.5.2.2 (Ahem) Database Systems Unit 5 Database Implementation: SQL Data Definition Language Learning Goals In this unit you will learn how to transfer a logical data model into a physical database, how to extend or

More information

Proposed solutions Project Assignment #1 (SQL)

Proposed solutions Project Assignment #1 (SQL) Proposed solutions Project Assignment #1 (SQL) (a) Database creation: create table sailor (sname CHAR(30), rating INTEGER) create table boat (bname CHAR (30), color CHAR (15), rating INTEGER) create table

More information

CS 338 Join, Aggregate and Group SQL Queries

CS 338 Join, Aggregate and Group SQL Queries CS 338 Join, Aggregate and Group SQL Queries Bojana Bislimovska Winter 2016 Outline SQL joins Aggregate functions in SQL Grouping in SQL HAVING clause SQL Joins Specifies a table resulting from a join

More information

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 Outline More Complex SQL Retrieval Queries

More information

Summary on Chapter 4 Basic SQL

Summary on Chapter 4 Basic SQL Summary on Chapter 4 Basic SQL SQL Features Basic SQL DDL o Includes the CREATE statements o Has a comprehensive set of SQL data types o Can specify key, referential integrity, and other constraints Basic

More information

The Relational Model. Why Study the Relational Model? Relational Database: Definitions

The Relational Model. Why Study the Relational Model? Relational Database: Definitions The Relational Model Database Management Systems, R. Ramakrishnan and J. Gehrke 1 Why Study the Relational Model? Most widely used model. Vendors: IBM, Microsoft, Oracle, Sybase, etc. Legacy systems in

More information

Lab Assignment 0. 1. Creating a Relational Database Schema from ER Diagram, Populating the Database and Querying over the database with SQL

Lab Assignment 0. 1. Creating a Relational Database Schema from ER Diagram, Populating the Database and Querying over the database with SQL SS Chung Lab Assignment 0 1. Creating a Relational Database Schema from ER Diagram, Populating the Database and Querying over the database with SQL 1. Creating the COMPANY database schema using SQL (DDL)

More information

The Relational Model. Why Study the Relational Model? Relational Database: Definitions. Chapter 3

The Relational Model. Why Study the Relational Model? Relational Database: Definitions. Chapter 3 The Relational Model Chapter 3 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1 Why Study the Relational Model? Most widely used model. Vendors: IBM, Informix, Microsoft, Oracle, Sybase,

More information

The Relational Model. Why Study the Relational Model?

The Relational Model. Why Study the Relational Model? The Relational Model Chapter 3 Instructor: Vladimir Zadorozhny vladimir@sis.pitt.edu Information Science Program School of Information Sciences, University of Pittsburgh 1 Why Study the Relational Model?

More information

The Relational Algebra

The Relational Algebra The Relational Algebra Relational set operators: The data in relational tables are of limited value unless the data can be manipulated to generate useful information. Relational Algebra defines the theoretical

More information

ER & EER to Relational Mapping. Chapter 9 1

ER & EER to Relational Mapping. Chapter 9 1 ER & EER to Relational Mapping Chapter 9 1 Figure 3.2 ER schema diagram for the company database. Fname Minit Lname Number Name Address N 1 WORKS_FOR Name Locations Sex Salary Ssn Bdate EMPLOYEE NumberOfEmployees

More information

SQL: QUERIES, CONSTRAINTS, TRIGGERS

SQL: QUERIES, CONSTRAINTS, TRIGGERS 5 SQL: QUERIES, CONSTRAINTS, TRIGGERS Online material is available for all exercises in this chapter on the book s webpage at http://www.cs.wisc.edu/~dbbook This includes scripts to create tables for each

More information

Lecture 6. SQL, Logical DB Design

Lecture 6. SQL, Logical DB Design Lecture 6 SQL, Logical DB Design Relational Query Languages A major strength of the relational model: supports simple, powerful querying of data. Queries can be written intuitively, and the DBMS is responsible

More information

New York University Computer Science Department Courant Institute of Mathematical Sciences

New York University Computer Science Department Courant Institute of Mathematical Sciences New York University Computer Science Department Courant Institute of Mathematical Sciences Homework #5 Solutions Course Title: Database Systems Instructor: Jean-Claude Franchitti Course Number: CSCI-GA.2433-001

More information

Lecture 4: More SQL and Relational Algebra

Lecture 4: More SQL and Relational Algebra CPSC 421 Database Management Systems Lecture 4: More SQL and Relational Algebra * Some material adapted from R. Ramakrishnan, L. Delcambre, and B. Ludaescher Today s Agenda Go over last week s quiz New

More information

10CS54: DATABASE MANAGEMENT SYSTEM

10CS54: DATABASE MANAGEMENT SYSTEM CS54: DATABASE MANAGEMENT SYSTEM QUESTION BANK Chapter 1: Introduction to Database Systems Objective: Databases and data base system have become an essential component of everyday life in modern society.

More information

SQL NULL s, Constraints, Triggers

SQL NULL s, Constraints, Triggers CS145 Lecture Notes #9 SQL NULL s, Constraints, Triggers Example schema: CREATE TABLE Student (SID INTEGER PRIMARY KEY, name CHAR(30), age INTEGER, GPA FLOAT); CREATE TABLE Take (SID INTEGER, CID CHAR(10),

More information

More on SQL. Juliana Freire. Some slides adapted from J. Ullman, L. Delcambre, R. Ramakrishnan, G. Lindstrom and Silberschatz, Korth and Sudarshan

More on SQL. Juliana Freire. Some slides adapted from J. Ullman, L. Delcambre, R. Ramakrishnan, G. Lindstrom and Silberschatz, Korth and Sudarshan More on SQL Some slides adapted from J. Ullman, L. Delcambre, R. Ramakrishnan, G. Lindstrom and Silberschatz, Korth and Sudarshan SELECT A1, A2,, Am FROM R1, R2,, Rn WHERE C1, C2,, Ck Interpreting a Query

More information

The Relational Model. Ramakrishnan&Gehrke, Chapter 3 CS4320 1

The Relational Model. Ramakrishnan&Gehrke, Chapter 3 CS4320 1 The Relational Model Ramakrishnan&Gehrke, Chapter 3 CS4320 1 Why Study the Relational Model? Most widely used model. Vendors: IBM, Informix, Microsoft, Oracle, Sybase, etc. Legacy systems in older models

More information

More SQL: Assertions, Views, and Programming Techniques

More SQL: Assertions, Views, and Programming Techniques 9 More SQL: Assertions, Views, and Programming Techniques In the previous chapter, we described several aspects of the SQL language, the standard for relational databases. We described the SQL statements

More information

Query-by-Example (QBE)

Query-by-Example (QBE) Query-by-Example (QBE) Module 3, Lecture 6 Example is the school of mankind, and they will learn at no other. -- Edmund Burke (1729-1797) Database Management Systems, R. Ramakrishnan 1 QBE: Intro A GUI

More information

Database Security. Chapter 21

Database Security. Chapter 21 Database Security Chapter 21 Introduction to DB Security Secrecy: Users should not be able to see things they are not supposed to. E.g., A student can t see other students grades. Integrity: Users should

More information

3. Relational Model and Relational Algebra

3. Relational Model and Relational Algebra ECS-165A WQ 11 36 3. Relational Model and Relational Algebra Contents Fundamental Concepts of the Relational Model Integrity Constraints Translation ER schema Relational Database Schema Relational Algebra

More information

Oracle SQL. Course Summary. Duration. Objectives

Oracle SQL. Course Summary. Duration. Objectives Oracle SQL Course Summary Identify the major structural components of the Oracle Database 11g Create reports of aggregated data Write SELECT statements that include queries Retrieve row and column data

More information

Introduction to database design

Introduction to database design Introduction to database design KBL chapter 5 (pages 127-187) Rasmus Pagh Some figures are borrowed from the ppt slides from the book used in the course, Database systems by Kiefer, Bernstein, Lewis Copyright

More information

Answer Key. UNIVERSITY OF CALIFORNIA College of Engineering Department of EECS, Computer Science Division

Answer Key. UNIVERSITY OF CALIFORNIA College of Engineering Department of EECS, Computer Science Division Answer Key UNIVERSITY OF CALIFORNIA College of Engineering Department of EECS, Computer Science Division CS186 Fall 2003 Eben Haber Midterm Midterm Exam: Introduction to Database Systems This exam has

More information

CS2Bh: Current Technologies. Introduction to XML and Relational Databases. The Relational Model. The relational model

CS2Bh: Current Technologies. Introduction to XML and Relational Databases. The Relational Model. The relational model CS2Bh: Current Technologies Introduction to XML and Relational Databases Spring 2005 The Relational Model CS2 Spring 2005 (LN6) 1 The relational model Proposed by Codd in 1970. It is the dominant data

More information

Oracle Database: SQL and PL/SQL Fundamentals

Oracle Database: SQL and PL/SQL Fundamentals Oracle University Contact Us: +966 12 739 894 Oracle Database: SQL and PL/SQL Fundamentals Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals training is designed to

More information

EECS 647: Introduction to Database Systems

EECS 647: Introduction to Database Systems EECS 647: Introduction to Database Systems Instructor: Luke Huan Spring 2013 Administrative Take home background survey is due this coming Friday The grader of this course is Ms. Xiaoli Li and her email

More information

Oracle Database: SQL and PL/SQL Fundamentals

Oracle Database: SQL and PL/SQL Fundamentals Oracle University Contact Us: 1.800.529.0165 Oracle Database: SQL and PL/SQL Fundamentals Duration: 5 Days What you will learn This course is designed to deliver the fundamentals of SQL and PL/SQL along

More information

Information Systems SQL. Nikolaj Popov

Information Systems SQL. Nikolaj Popov Information Systems SQL Nikolaj Popov Research Institute for Symbolic Computation Johannes Kepler University of Linz, Austria popov@risc.uni-linz.ac.at Outline SQL Table Creation Populating and Modifying

More information

Relational Databases

Relational Databases Relational Databases Jan Chomicki University at Buffalo Jan Chomicki () Relational databases 1 / 18 Relational data model Domain domain: predefined set of atomic values: integers, strings,... every attribute

More information

Procedural Extension to SQL using Triggers. SS Chung

Procedural Extension to SQL using Triggers. SS Chung Procedural Extension to SQL using Triggers SS Chung 1 Content 1 Limitations of Relational Data Model for performing Information Processing 2 Database Triggers in SQL 3 Using Database Triggers for Information

More information

SUBQUERIES AND VIEWS. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 6

SUBQUERIES AND VIEWS. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 6 SUBQUERIES AND VIEWS CS121: Introduction to Relational Database Systems Fall 2015 Lecture 6 String Comparisons and GROUP BY 2! Last time, introduced many advanced features of SQL, including GROUP BY! Recall:

More information

ICAB4136B Use structured query language to create database structures and manipulate data

ICAB4136B Use structured query language to create database structures and manipulate data ICAB4136B Use structured query language to create database structures and manipulate data Release: 1 ICAB4136B Use structured query language to create database structures and manipulate data Modification

More information

Lecture 6: Query optimization, query tuning. Rasmus Pagh

Lecture 6: Query optimization, query tuning. Rasmus Pagh Lecture 6: Query optimization, query tuning Rasmus Pagh 1 Today s lecture Only one session (10-13) Query optimization: Overview of query evaluation Estimating sizes of intermediate results A typical query

More information

Instant SQL Programming

Instant SQL Programming Instant SQL Programming Joe Celko Wrox Press Ltd. INSTANT Table of Contents Introduction 1 What Can SQL Do for Me? 2 Who Should Use This Book? 2 How To Use This Book 3 What You Should Know 3 Conventions

More information

Functional Dependency and Normalization for Relational Databases

Functional Dependency and Normalization for Relational Databases Functional Dependency and Normalization for Relational Databases Introduction: Relational database design ultimately produces a set of relations. The implicit goals of the design activity are: information

More information

Structured Query Language (SQL)

Structured Query Language (SQL) Objectives of SQL Structured Query Language (SQL) o Ideally, database language should allow user to: create the database and relation structures; perform insertion, modification, deletion of data from

More information

History of SQL. Relational Database Languages. Tuple relational calculus ALPHA (Codd, 1970s) QUEL (based on ALPHA) Datalog (rule-based, like PROLOG)

History of SQL. Relational Database Languages. Tuple relational calculus ALPHA (Codd, 1970s) QUEL (based on ALPHA) Datalog (rule-based, like PROLOG) Relational Database Languages Tuple relational calculus ALPHA (Codd, 1970s) QUEL (based on ALPHA) Datalog (rule-based, like PROLOG) Domain relational calculus QBE (used in Access) History of SQL Standards:

More information

INFO/CS 330: Applied Database Systems

INFO/CS 330: Applied Database Systems INFO/CS 330: Applied Database Systems Introduction to Database Security Johannes Gehrke johannes@cs.cornell.edu http://www.cs.cornell.edu/johannes Introduction to DB Security Secrecy:Users should not be

More information

1 Structured Query Language: Again. 2 Joining Tables

1 Structured Query Language: Again. 2 Joining Tables 1 Structured Query Language: Again So far we ve only seen the basic features of SQL. More often than not, you can get away with just using the basic SELECT, INSERT, UPDATE, or DELETE statements. Sometimes

More information

Relational Database: Additional Operations on Relations; SQL

Relational Database: Additional Operations on Relations; SQL Relational Database: Additional Operations on Relations; SQL Greg Plaxton Theory in Programming Practice, Fall 2005 Department of Computer Science University of Texas at Austin Overview The course packet

More information

Introduction to Microsoft Jet SQL

Introduction to Microsoft Jet SQL Introduction to Microsoft Jet SQL Microsoft Jet SQL is a relational database language based on the SQL 1989 standard of the American Standards Institute (ANSI). Microsoft Jet SQL contains two kinds of

More information

Databases and BigData

Databases and BigData Eduardo Cunha de Almeida eduardo.almeida@uni.lu Outline of the course Introduction Database Systems (E. Almeida) Distributed Hash Tables and P2P (C. Cassagnes) NewSQL (D. Kim and J. Meira) NoSQL (D. Kim)

More information

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database: SQL and PL/SQL Fundamentals NEW Oracle University Contact Us: + 38516306373 Oracle Database: SQL and PL/SQL Fundamentals NEW Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals training delivers the

More information

Database Management Systems. Chapter 1

Database Management Systems. Chapter 1 Database Management Systems Chapter 1 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 2 What Is a Database/DBMS? A very large, integrated collection of data. Models real-world scenarios

More information

Lab Manual. Database Systems COT-313 & Database Management Systems Lab IT-216

Lab Manual. Database Systems COT-313 & Database Management Systems Lab IT-216 Lab Manual Database Systems COT-313 & Database Management Systems Lab IT-216 Lab Instructions Several practicals / programs? Whether an experiment contains one or several practicals /programs One practical

More information

Outline. Data Modeling. Conceptual Design. ER Model Basics: Entities. ER Model Basics: Relationships. Ternary Relationships. Yanlei Diao UMass Amherst

Outline. Data Modeling. Conceptual Design. ER Model Basics: Entities. ER Model Basics: Relationships. Ternary Relationships. Yanlei Diao UMass Amherst Outline Data Modeling Yanlei Diao UMass Amherst v Conceptual Design: ER Model v Relational Model v Logical Design: from ER to Relational Slides Courtesy of R. Ramakrishnan and J. Gehrke 1 2 Conceptual

More information

Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL Chapter 9 Joining Data from Multiple Tables Oracle 10g: SQL Objectives Identify a Cartesian join Create an equality join using the WHERE clause Create an equality join using the JOIN keyword Create a non-equality

More information

{ PreviousEducation ( CollegeName, StartDate, EndDate, { Degree (DegreeName, Month, Year) }, { Transcript (CourseName, Semester, Year, Grade) } ) }

{ PreviousEducation ( CollegeName, StartDate, EndDate, { Degree (DegreeName, Month, Year) }, { Transcript (CourseName, Semester, Year, Grade) } ) } Tutorial 3 Solution Exercise1: Exercise 2: { PreviousEducation ( CollegeName, StartDate, EndDate, { Degree (DegreeName, Month, Year) }, { Transcript (CourseName, Semester, Year, Grade) } ) } Exercise 3:

More information

There are five fields or columns, with names and types as shown above.

There are five fields or columns, with names and types as shown above. 3 THE RELATIONAL MODEL Exercise 3.1 Define the following terms: relation schema, relational database schema, domain, attribute, attribute domain, relation instance, relation cardinality, andrelation degree.

More information

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff D80198GC10 Oracle Database 12c SQL and Fundamentals Summary Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff Level Professional Delivery Method Instructor-led

More information

Chapter 5: FUNCTIONAL DEPENDENCIES AND NORMALIZATION FOR RELATIONAL DATABASES

Chapter 5: FUNCTIONAL DEPENDENCIES AND NORMALIZATION FOR RELATIONAL DATABASES 1 Chapter 5: FUNCTIONAL DEPENDENCIES AND NORMALIZATION FOR RELATIONAL DATABASES INFORMAL DESIGN GUIDELINES FOR RELATION SCHEMAS We discuss four informal measures of quality for relation schema design in

More information

Week 4 & 5: SQL. SQL as a Query Language

Week 4 & 5: SQL. SQL as a Query Language Week 4 & 5: SQL The SQL Query Language Select Statements Joins, Aggregate and Nested Queries Insertions, Deletions and Updates Assertions, Views, Triggers and Access Control SQL 1 SQL as a Query Language

More information

Review Entity-Relationship Diagrams and the Relational Model. Data Models. Review. Why Study the Relational Model? Steps in Database Design

Review Entity-Relationship Diagrams and the Relational Model. Data Models. Review. Why Study the Relational Model? Steps in Database Design Review Entity-Relationship Diagrams and the Relational Model CS 186, Fall 2007, Lecture 2 R & G, Chaps. 2&3 Why use a DBMS? OS provides RAM and disk A relationship, I think, is like a shark, you know?

More information

SQL Simple Queries. Chapter 3.1 V3.0. Copyright @ Napier University Dr Gordon Russell

SQL Simple Queries. Chapter 3.1 V3.0. Copyright @ Napier University Dr Gordon Russell SQL Simple Queries Chapter 3.1 V3.0 Copyright @ Napier University Dr Gordon Russell Introduction SQL is the Structured Query Language It is used to interact with the DBMS SQL can Create Schemas in the

More information

Advance DBMS. Structured Query Language (SQL)

Advance DBMS. Structured Query Language (SQL) Structured Query Language (SQL) Introduction Commercial database systems use more user friendly language to specify the queries. SQL is the most influential commercially marketed product language. Other

More information

CHAPTER 8: SQL-99: SCHEMA DEFINITION, BASIC CONSTRAINTS, AND QUERIES

CHAPTER 8: SQL-99: SCHEMA DEFINITION, BASIC CONSTRAINTS, AND QUERIES Chapter 8: SQL-99: Schema Definition, Basic Constraints, and Queries 1 CHAPTER 8: SQL-99: SCHEMA DEFINITION, BASIC CONSTRAINTS, AND QUERIES Answers to Selected Exercises 8. 7 Consider the database shown

More information

6 QUERY-BY-EXAMPLE (QBE)

6 QUERY-BY-EXAMPLE (QBE) 6 QUERY-BY-EXAMPLE (QBE) Example is always more efficacious than precept. Samuel Johnson 6.1 INTRODUCTION Query-by-Example (QBE) is another language for querying (and, like SQL, for creating and modifying)

More information

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA www.sybex.com

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA www.sybex.com Essential SQL 2 Essential SQL This bonus chapter is provided with Mastering Delphi 6. It is a basic introduction to SQL to accompany Chapter 14, Client/Server Programming. RDBMS packages are generally

More information

CS143 Notes: Views & Authorization

CS143 Notes: Views & Authorization CS143 Notes: Views & Authorization Book Chapters (4th) Chapter 4.7, 6.5-6 (5th) Chapter 4.2, 8.6 (6th) Chapter 4.4, 5.3 Views What is a view? A virtual table created on top of other real tables Almost

More information

Data Modeling. Database Systems: The Complete Book Ch. 4.1-4.5, 7.1-7.4

Data Modeling. Database Systems: The Complete Book Ch. 4.1-4.5, 7.1-7.4 Data Modeling Database Systems: The Complete Book Ch. 4.1-4.5, 7.1-7.4 Data Modeling Schema: The structure of the data Structured Data: Relational, XML-DTD, etc Unstructured Data: CSV, JSON But where does

More information

4. SQL. Contents. Example Database. CUSTOMERS(FName, LName, CAddress, Account) PRODUCTS(Prodname, Category) SUPPLIERS(SName, SAddress, Chain)

4. SQL. Contents. Example Database. CUSTOMERS(FName, LName, CAddress, Account) PRODUCTS(Prodname, Category) SUPPLIERS(SName, SAddress, Chain) ECS-165A WQ 11 66 4. SQL Contents Basic Queries in SQL (select statement) Set Operations on Relations Nested Queries Null Values Aggregate Functions and Grouping Data Definition Language Constructs Insert,

More information

VIEWS virtual relation data duplication consistency problems

VIEWS virtual relation data duplication consistency problems VIEWS A virtual relation that is defined from other preexisting relations Called the defining relations of the view A view supports multiple user perspectives on the database corresponding to different

More information

SQL SELECT Query: Intermediate

SQL SELECT Query: Intermediate SQL SELECT Query: Intermediate IT 4153 Advanced Database J.G. Zheng Spring 2012 Overview SQL Select Expression Alias revisit Aggregate functions - complete Table join - complete Sub-query in where Limiting

More information

The Relational Data Model and Relational Database Constraints

The Relational Data Model and Relational Database Constraints The Relational Data Model and Relational Database Constraints Chapter Outline Relational Model Concepts Relational Model Constraints and Relational Database Schemas Update Operations and Dealing with Constraint

More information

SQL Server. 2012 for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

SQL Server. 2012 for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach TRAINING & REFERENCE murach's SQL Server 2012 for developers Bryan Syverson Joel Murach Mike Murach & Associates, Inc. 4340 N. Knoll Ave. Fresno, CA 93722 www.murach.com murachbooks@murach.com Expanded

More information

Chapter 13: Query Optimization

Chapter 13: Query Optimization Chapter 13: Query Optimization Database System Concepts, 6 th Ed. See www.db-book.com for conditions on re-use Chapter 13: Query Optimization Introduction Transformation of Relational Expressions Catalog

More information

Comp 5311 Database Management Systems. 3. Structured Query Language 1

Comp 5311 Database Management Systems. 3. Structured Query Language 1 Comp 5311 Database Management Systems 3. Structured Query Language 1 1 Aspects of SQL Most common Query Language used in all commercial systems Discussion is based on the SQL92 Standard. Commercial products

More information

Review: Participation Constraints

Review: Participation Constraints Review: Participation Constraints Does every department have a manager? If so, this is a participation constraint: the participation of Departments in Manages is said to be total (vs. partial). Every did

More information

Oracle Database 10g: Introduction to SQL

Oracle Database 10g: Introduction to SQL Oracle University Contact Us: 1.800.529.0165 Oracle Database 10g: Introduction to SQL Duration: 5 Days What you will learn This course offers students an introduction to Oracle Database 10g database technology.

More information

MOC 20461C: Querying Microsoft SQL Server. Course Overview

MOC 20461C: Querying Microsoft SQL Server. Course Overview MOC 20461C: Querying Microsoft SQL Server Course Overview This course provides students with the knowledge and skills to query Microsoft SQL Server. Students will learn about T-SQL querying, SQL Server

More information

Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1

Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1 Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1 A feature of Oracle Rdb By Ian Smith Oracle Rdb Relational Technology Group Oracle Corporation 1 Oracle Rdb Journal SQL:1999 and Oracle Rdb V7.1 The

More information

IT2304: Database Systems 1 (DBS 1)

IT2304: Database Systems 1 (DBS 1) : Database Systems 1 (DBS 1) (Compulsory) 1. OUTLINE OF SYLLABUS Topic Minimum number of hours Introduction to DBMS 07 Relational Data Model 03 Data manipulation using Relational Algebra 06 Data manipulation

More information

Introduction to Querying & Reporting with SQL Server

Introduction to Querying & Reporting with SQL Server 1800 ULEARN (853 276) www.ddls.com.au Introduction to Querying & Reporting with SQL Server Length 5 days Price $4169.00 (inc GST) Overview This five-day instructor led course provides students with the

More information

A basic create statement for a simple student table would look like the following.

A basic create statement for a simple student table would look like the following. Creating Tables A basic create statement for a simple student table would look like the following. create table Student (SID varchar(10), FirstName varchar(30), LastName varchar(30), EmailAddress varchar(30));

More information

Intermediate SQL C H A P T E R4. Practice Exercises. 4.1 Write the following queries in SQL:

Intermediate SQL C H A P T E R4. Practice Exercises. 4.1 Write the following queries in SQL: C H A P T E R4 Intermediate SQL Practice Exercises 4.1 Write the following queries in SQL: a. Display a list of all instructors, showing their ID, name, and the number of sections that they have taught.

More information

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

SQL - QUICK GUIDE. Allows users to access data in relational database management systems. http://www.tutorialspoint.com/sql/sql-quick-guide.htm SQL - QUICK GUIDE Copyright tutorialspoint.com What is SQL? SQL is Structured Query Language, which is a computer language for storing, manipulating

More information

Programming with SQL

Programming with SQL Unit 43: Programming with SQL Learning Outcomes A candidate following a programme of learning leading to this unit will be able to: Create queries to retrieve information from relational databases using

More information

SQL DATA DEFINITION: KEY CONSTRAINTS. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 7

SQL DATA DEFINITION: KEY CONSTRAINTS. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 7 SQL DATA DEFINITION: KEY CONSTRAINTS CS121: Introduction to Relational Database Systems Fall 2015 Lecture 7 Data Definition 2 Covered most of SQL data manipulation operations Continue exploration of SQL

More information