1 Views and Null values. 2 What does this return? SELECT B.bid, COUNT(*) FROM Boats B, Reserves R WHERE R.bid=B.bid and B.color=‘red’ GROUP BY B.bid For.

Slides:



Advertisements
Similar presentations
1 Advanced SQL Queries. 2 Example Tables Used Reserves sidbidday /10/04 11/12/04 Sailors sidsnameratingage Dustin Lubber Rusty.
Advertisements

Review Session ER and Relational –ER  Relational –Constraints, Weak Entities, Aggregation, ISA Relational Algebra  Relational Calculus –Selections/Projections/Joins/Division.
Introduction to Database Systems 1 SQL: The Query Language Relation Model : Topic 4.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5.
CS 166: Database Management Systems
SQL: Queries, Constraints, Triggers
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
Database Management Systems 1 Raghu Ramakrishnan SQL: Queries, Programming, Triggers Chpt 5.
SQL: The Query Language Jianlin Feng School of Software SUN YAT-SEN UNIVERSITY courtesy of Joe Hellerstein and etc for some slides.
SQL Part II: Advanced Queries. 421B: Database Systems - SQL Queries II 2 Aggregation q Significant extension of relational algebra q “Count the number.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5.
CS 405G: Introduction to Database Systems
111 A DMINISTRATIVE Exam Oct 19, :30pm in 3005 (usual room) No class on Oct 21 What topic to do for review? November 18 th away for conference.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5.
1 Reminder We have covered: –Creating tables –Converting ER diagrams to table definitions Today we’ll talk about: –Altering tables –Inserting and deleting.
SQL 2 – The Sequel R&G, Chapter 5 Lecture 10. Administrivia Homework 2 assignment now available –Due a week from Sunday Midterm exam will be evening of.
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 90 Database Systems I SQL Queries.
1 SQL (Simple Query Language). 2 Query Components A query can contain the following clauses –select –from –where –group by –having –order by Only select.
FALL 2004CENG 351 File Structures and Data Management1 SQL: Structured Query Language Chapter 5.
Rutgers University SQL: Queries, Constraints, Triggers 198:541 Rutgers University.
1 Sub-queries and Views. 2 A Complex Query We would like to create a table containing 3 columns: –Sailor id –Sailor age –Age of the oldest Sailor How.
1 Views. 2 Views A view is a "virtual table" defined using a query You can use a view as if it were a table, even though it doesn't contain data The view.
1 Table Alteration. 2 Altering Tables Table definition can be altered after its creation –Adding columns –Changing columns’ definition –Dropping columns.
1 Views. 2 What are views good for?(1) Simplifying complex queries: we saw one example. Here is another example that allows the user to "pretend" that.
1 Rewriting Minus Queries Using Not In SELECT S.sname FROM Sailors S, Boats B, Reserves R WHERE S.sid = R.sid and R.bid = B.bid and B.color = ‘red’ MINUS.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
1 The Oracle Database System Querying the Data Database Course The Hebrew University of Jerusalem.
1 Views. 2 What are views good for? (1) Simplifying complex queries: We saw one example. Here is another that allows the user to "pretend" that there.
1 SQL: Structured Query Language Chapter 5. 2 SQL and Relational Calculus relationalcalculusAlthough relational algebra is useful in the analysis of query.
1 Moving a Java Program into a Database. 2 Motivation We would like to be able to run a Java program from within Oracle. This will allow us to: –call.
1 Rewriting Intersect Queries Using In 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.
1 Advanced SQL. 2 Consider the following relations: –pupil (pupil_name, address, class, birthyear) –subject (subject_name, class, teacher) –grades (pupil_name,
CSC343 – Introduction to Databases - A. Vaisman1 SQL: Queries, Programming, Triggers.
1 Relational Algebra and Calculus Chapter 4. 2 Relational Query Languages  Query languages: Allow manipulation and retrieval of data from a database.
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L6_SQL(1) 1 SQL: Queries, Constraints, Triggers Chapter 5 – Part 1.
10/20/20151 Introduction to SQL and the Relational Model ICOS Big Data Summer Camp June 2, 2015 Mike Anderson (slides from Mike Cafarella)
SQL Part I: Standard Queries. COMP-421: Database Systems - SQL Queries I 2 Example Instances sid sname rating age 22 debby debby lilly.
SQL Examples CS3754 Class Note 11 CS3754 Class Note 11, John Shieh,
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
SQL: Queries, Programming, Triggers. Example Instances We will use these instances of the Sailors and Reserves relations in our examples. If the key for.
ICS 321 Fall 2009 SQL: Queries, Constraints, Triggers Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa 9/8/20091Lipyeow.
1 Database Systems ( 資料庫系統 ) October 24, 2005 Lecture #5.
1 SQL: Queries, Constraints, Triggers Chapter 5. 2 Example Instances R1 S1 S2  We will use these instances of the Sailors and Reserves relations in our.
The Oracle Database System. Connecting to the Database At the command line prompt, write: sqlplus In the beginning your password.
CMPT 258 Database Systems SQL Queries (Chapter 5).
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Management Systems Chapter 5 SQL.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5.
SQL: The Query Language Part 1 R &G - Chapter 5 The important thing is not to stop questioning. Albert Einstein.
1 SQL: The Query Language. 2 Example Instances R1 S1 S2 v We will use these instances of the Sailors and Reserves relations in our examples. v If the.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Basic SQL Queries.
1 CS122A: Introduction to Data Management Lecture 9 SQL II: Nested Queries, Aggregation, Grouping Instructor: Chen Li.
DataBase - Check 01 DataBase 2 nd year Computer Science & Engineer 1.
1 SQL Structured Query Language. Query Language SQL is a query language Used to examine data in the database SQL queries do not change the contents of.
1 SQL Structured Query Language. Query Language SQL is a query language Used to examine data in the database SQL queries do not change the contents of.
Basic SQL Queries Go over example queries, like 10 > ALL.
COP Introduction to Database Structures
© פרופ' יהושע שגיב, האוניברסיטה העברית
Structured Query Language
01/31/11 SQL Examples Edited by John Shieh CS3754 Classnote #10.
SQL The Query Language R & G - Chapter 5
Database Systems October 14, 2009 Lecture #5.
Basic SQL Lecture 6 Fall
Database Applications (15-415) SQL-Part II Lecture 9, February 04, 2018 Mohammad Hammoud.
CS 405G: Introduction to Database Systems
SQL: Queries, Constraints, Triggers
SQL: The Query Language Part 1
קורס קבצים ובסיסי נתונים
CS4222 Principles of Database System
SQL: Structured Query Language
SQL: The Query Language (Part III)
Presentation transcript:

1 Views and Null values

2 What does this return? SELECT B.bid, COUNT(*) FROM Boats B, Reserves R WHERE R.bid=B.bid and B.color=‘red’ GROUP BY B.bid For every reserved red boat : (id,number of reservations) What would happen if we put the condition about the color in the HAVING clause?

3 SELECT B.bid, COUNT(*) FROM Boats B, Reserves R WHERE R.bid=B.bid GROUP BY B.bid, B.color HAVING B.color=‘red’ We also have to put the color in the grouping list!

4 What does this return? Can we move the condition in the HAVING to the WHERE? SELECT bname FROM Boats B, Reserves R WHERE R.bid=B.bid GROUP BY bid, bname HAVING count(DISTINCT day) <= 5 No! Aggregate functions are not allowed in WHERE Names of Boats that were not Reserved on more than 5 days

5 The Color for which there are the most boats..? SELECT color FROM Boats B GROUP BY color HAVING max(count(bid)) What is wrong with this? How would you fix it?

6 The Color for which there are the most boats SELECT color FROM Boats B GROUP BY color HAVING count(bid) >= ALL (SELECT count(bid) FROM Boats GROUP BY Color)

7 Aggregation Instead of Exists Aggregation can take the place of exists. What does this return? SELECT color FROM Boats B1 WHERE NOT EXISTS( SELECT * FROM Boats B2 WHERE B1.bid <> B2.bid AND B1.color=B2.color) The color of boats which there are no other boats with the same color

8 Aggregation Instead of Exists SELECT color FROM Boats B1 GROUP BY color HAVING count(bid) = 1 Somewhat simpler …

9 Sub-queries and Views

10 A Complex Query We would like to create a table containing 3 columns: –Sailor id –Sailor age –Age of the oldest Sailor How can this be done?

11 Attempt 1 SELECT S.sid, S.age, MAX(S.age) FROM Sailors S; Why is this wrong? Error: “ Not a single-group group function ” You can either select single results from each group (grouping), or not, but not both.

12 Attempt 2 SELECT S.sid, S.age, MAX(S.age) FROM Sailors S GROUP BY S.sid, S.age; Why is this wrong? For every sailor, this would give his own age in both columns

13 Solution 1: Sub-query in FROM SELECT S.sid, S.age, M.mxage FROM Sailors S,(SELECT MAX(S2.age) as mxage FROM Sailors S2) M; We can put a query in the FROM clause instead of a table (this is like creating a temporary local table) The sub-query in the FROM clause must be renamed with a range variable (M in this case).

14 Solution 2: Sub-query in SELECT SELECT S.sid, S.age, (SELECT MAX(S2.age) FROM Sailors S2) FROM Sailors S; A sub-query in the SELECT clause must return at most one value for each row returned by the outer query.

15 Another Example of a Sub-query in SELECT SELECT S.sid, S.age, (SELECT MAX(S2.age) FROM Sailors S2 WHERE S2.age<S.age) FROM Sailors S; What does this query return? For each sailor S, the age of the oldest sailor among the sailors younger than S Note the use of S (defined in the outer query) in the sub-query.

16 Another Example of a Sub-query in FROM?? SELECT S.sid, S.age, M.mxage FROM Sailors S, (SELECT MAX(S2.age) as mxage FROM Sailors S2 WHERE S2.age<S.age) M; Subqueries in the From clause do not have access to other relations. For example, the following is wrong:

17 Solution 3: Create a Table CREATE TABLE MaxAge as SELECT MAX(S.age) as mxage FROM Sailors S; SELECT S.sid, S.age, M.mxage FROM Sailors S, MaxAge M; MUST Rename! Problem: how to update MaxAge table?

18 Views A view is a "virtual table" defined using a query You can use a view as if it were a table, even though it doesn't contain data The view is computed every time that it is referenced!

19 Advantages and Disadvantages Advantages: –no memory used for views –update of underlying tables does not require updating views –gives query processor more choices for optimizing Disadvantages: –must be recomputed every time used –if tables that view uses are dropped, view data is lost

20 Solution 4: Views A View looks like a table but acts like a query CREATE OR REPLACE VIEW MaxAge as SELECT MAX(S.age) as mxage FROM Sailors S; SELECT S.sid, S.age, M.mxage FROM Sailors S, MaxAge M; MUST Rename!

21 Views A view is a "virtual table" defined using a query You can use a view as if it were a table, even though it doesn't contain data The view is used as a ‘window’ to underlying tables The view is computed every time that it is referenced Changes can be done in both directions: View Table

22 Example Dept20AnnualView EnameAnnualSal Dustin Rusty CREATE OR REPLACE VIEW Dept20AnnualView as SELECT Ename, Sal*12 As AnnualSal FROM Emp Where dept=20; Emp EidEnameDeptAgesal Dustin Lubber Rusty Querying Dept20AnnualView will give results according to the updated data in Emp

23 Example 2: Products table CREATE VIEW ProductsAboveAveragePrice AS SELECT ProductName,UnitPrice FROM Products WHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products) ProductNameQuantityUnitPrice Milk1004 Eggs8710 Bread645

24 What are views good for?(1) Simplifying complex queries Here is another example that allows the user to "pretend" that there is a single table in the database: CREATE OR REPLACE VIEW SRB as SELECT S.sid, sname, rating, age, R.bid, day, bname, color FROM Sailors S, Boats B, Reserves R WHERE S.sid = R.sid and R.bid = B.bid

25 What are views good for?(2) SELECT sname FROM SRB WHERE bid=‘103’ Find names of Sailors who reserved boat 103 using SRB

26 What are views good for?(3) Security issues – preventing unauthorized access. Example: hiding the rating value CREATE VIEW SailorInfo as SELECT sname, sid, age FROM Sailors grant SELECT on SailorInfo to joe;

27 Changing Tables through a View

28 Changing Tables through a View Changing a view changes the underlying tables We will specify the limitations on the changes we are allowed to perform on a view based on one table only The guiding principle: We cannot “access” a value which doesn’t appear in the view (but many changes do not require “accessing”)

29 Changing a table through a view EmpView EidEname Dustin Lubber Rusty CREATE OR REPLACE VIEW EmpView as SELECT Eid, Ename FROM Emp Emp EidEnameDeptAgesal Dustin Lubber Rusty What will happen if we now insert a new employee into the view? Generally, he will be inserted into the underlying table (Emp) But, there are many limitations

30 Basic case EmpView EidEname Dustin Lubber Rusty Insert into EmpView values(13, ‘Mike’); Emp EidEnameDeptAgesal Dustin Lubber Rusty EmpView EidEname Dustin Rusty Mike Emp EidEnameDeptAgesal Dustin Lubber Rusty Mike

31 You can insert a value to the view even if it will not appear in the view after insertion (it will appear in the underlying table). You can update a value appearing in the view so that the result will not appear in the view. This is true unless ‘with check option’ is specified.

32 Result not appearing in view OldEmp Eidage Insert into OldEmp values(13, 28); Emp EidEnameAge Dustin Lubber Rusty CREATE VIEW OldEmp as SELECT eid, age FROM emp Where age>50 OldEmp Eidage Emp EidEnameAge Dustin Lubber Rusty

33 Result not appearing in view OldEmp Eidage Update OldEmp set age=age-5 where Eid=31; Emp EidEnameAge Dustin Lubber Rusty CREATE VIEW OldEmp as SELECT eid, age FROM emp Where age>50 OldEmp Eidage 5859 Emp EidEnameAge Dustin Lubber Rusty 27 59

34 Result not appearing in view OldEmp Eidage Insert into OldEmp values(13, 28); Emp EidEnameAge Dustin Lubber Rusty CREATE VIEW OldEmp as SELECT eid, age FROM emp Where age>50 with check option ERROR!

35 Result not appearing in view OldEmp Eidage Update OldEmp set age=age-5 where Eid=31; Emp EidEnameAge Dustin Lubber Rusty CREATE VIEW OldEmp as SELECT eid, age FROM emp Where age>50 with check option ERROR!

36 Changing a Table through a View You can’t insert tuples into the view if the underlying table has non null columns not appearing in the view

37 OldEmp Eidage Insert into OldEmp values(13, 28); Emp EidEnameAge Dustin Lubber Rusty CREATE VIEW OldEmp as SELECT eid, age FROM emp Where age>50 OldEmp Eidage Emp EidEnameAge Dustin Lubber Rusty If Ename is defined as not null in Emp, this insertion would be illegal

38 You can’t insert or update the view if any of the view columns referenced in the command contains functions or calculations

39 Example Dept20AnnualView EnameAnnualSal Dustin Rusty CREATE OR REPLACE VIEW Dept20AnnualView as SELECT Ename, Sal*12 As AnnualSal FROM Emp Where dept=20; Emp EidEnameDeptAgesal Dustin Lubber Rusty Now you cannot insert or update values in Dept20AnnualView

40 You can’t insert, update or delete from the view if the view contains group by or distinct You cannot update a value which doesn’t appear in the view (this requires “accessing”) You cannot insert or update columns which do not appear in the view But if you delete a row, it will delete the values of columns which are not in the view as well (does not require “approaching”)

41 OldEmp Eidage Insert into OldEmp values(13, ‘Ben’,28); Emp EidEnameAge Dustin Lubber Rusty CREATE VIEW OldEmp as SELECT eid, age FROM emp Where age>50 ERROR! Update OldEmp set age=age-5 where Eid=22; No update

42 Result not appearing in view OldEmp Eidage Delete from OldEmp where Eid=58; Emp EidEnameAge Dustin Lubber Rusty CREATE VIEW OldEmp as SELECT eid, age FROM emp Where age>50 OldEmp Eidage 3152 Emp EidEnameAge Dustin Lubber 27 52

43 Only Values of Rows seen through the View Only Values of Columns seen through the View Insert No (Yes if CHECK) Yes Update (values after change) No (Yes if CHECK) Yes Update (values before change) Yes DeleteYesNo

44 CREATE VIEW OldSailors as SELECT * FROM Sailors WHERE age > 50; INSERT INTO OldSailors(sid,sname,age,rating) VALUES(12, ‘ Mary ’,49,10); When we select from OldSailors next time, we will not see Mary. But she will appear in Sailors! Allowed?Yes!

45 CREATE VIEW OldSailors as SELECT * FROM Sailors WHERE age > 50 WITH CHECK OPTION; INSERT INTO OldSailors(sid,sname,age,rating) VALUES(12, ‘ Joe ’,51,10); INSERT INTO OldSailors(sid,sname,age,rating) VALUES(12, ‘ Mary ’,49,10); No! Yes! Allowed?

46 Sailors(sid, sname, age, rating) CREATE VIEW SailorsInfo as SELECT sname, rating FROM Sailors INSERT INTO SailorsInfo VALUES( ‘ Joe ’,10); Allowed?No!

47 CREATE VIEW SailorsInfo as SELECT sname, rating, age FROM Sailors WHERE age>50; UPDATE SailorsInfo SET rating = 6 WHERE sname = ‘ Joe ’ ; UPDATE Sailors SET rating = 6 WHERE sname = ‘ Joe ’ and age>50; Only Joes who are older than 50 are updated. Implemented by adding the WHERE condition of view to WHERE condition of table Update

48 CREATE VIEW SailorsInfo2 as SELECT sname, rating, age FROM Sailors WHERE age>50; UPDATE SailorsInfo2 SET age = age - 1; Might cause tuples to "disappear from the view" Can prevent this with "WITH CHECK OPTION" Implemented as: UPDATE Sailors SET age = age - 1 WHERE age>50;

49 Updating Not Allowed if …? CREATE VIEW BestSailors as SELECT sname, rating, age FROM Sailors WHERE rating>8 WITH CHECK OPTION; UPDATE BestSailors SET rating=rating-1; … if there are sailors with 8<rating<=9

50 CREATE VIEW SailorsInfo3 as SELECT sname, rating + age as ra FROM Sailors WHERE age>50; UPDATE SailorsInfo3 SET ra = 7 WHERE sname = ‘ Joe ’ ; UPDATE SailorsInfo3 SET sname = ‘ Joe ’ WHERE ra = 7; Yes! No! Allowed?

51 Deleting Allowed CREATE VIEW SailorsInfo3 as SELECT sname, rating + age as ra FROM Sailors WHERE age>50; DELETE FROM SailorsInfo3 WHERE sname = ‘ Joe ’ and ra = 56; Joes visible through the view are deleted. Implemented as: DELETE FROM Sailors WHERE sname = ‘ Joe ’ and rating + age = 56 and age > 50;

52 Examples (1) UPDATE OldSailors SET rating = 10; CREATE VIEW OldSailors as SELECT * FROM Sailors WHERE age > 50; What changes? Updates rating of sailors older than 50

53 Examples (2) UPDATE OldSailors SET age = age +1 WHERE age <= 50; CREATE VIEW OldSailors as SELECT * FROM Sailors WHERE age > 50; What changes? Nothing!

54 Examples(3) DELETE FROM OldSailors; CREATE VIEW OldSailors as SELECT * FROM Sailors WHERE age > 50; DELETE FROM Sailors WHERE age > 50 Implementation What changes? Remove from Sailors the sailors that are older than 50

55 Inserting/Updating/Deleting Not Allowed when the view contains group by or distinct CREATE VIEW OldSailors as SELECT sname FROM Sailors GROUP BY sname HAVING MIN(age) > 50; DELETE FROM OldSailors; INSERT INTO OldSailors VALUES( ‘ Joe ’ ); No! Allowed?

56 Materialized Views What: A materialized view is a view that actually exists as a table Why: This can be more efficient than re- computing the view’s query each time it is accessed How: We specify how often the materialized view is refreshed and how

57 Null Values "As we know, There are known knowns. There are things we know we know. We also know There are known unknowns. That is to say We know there are some things We do not know.” - Donald Rumsfeld, US Defence Secretary

58 Null Values in Expressions The result of an arithmetic expression, over something that is null -> is null (e.g., null*10 = null) Three-valued logic: true, false, unknown

59 Three-Valued Logic Table pqp AND qp OR q True False True NullUnknownTrue FalseTrueFalseTrue False NullFalseUnknown NullTrueUnknownTrue NullFalse Unknown Null Unknown Two-Valued Logic Table pqp AND qp OR q True False True FalseTrueFalseTrue False

60 What will these return? SELECT S.sname FROM Sailors S WHERE S.age = null SELECT S.sname FROM Sailors S WHERE S.age != null Nothing!

61 ? ?

62 Null Values in Expressions (2) Tuples only pass the WHERE/HAVING condition if the WHERE/HAVING evaluate to true (not false or unknown) Null verification: –IS NULL (not ‘= NULL’) –IS NOT NULL (not ‘<> NULL’)

63 Examples If x is null, then: –x = 3 -> unknown –null = 3 -> unknown –x = x -> unknown –null = null -> unknown –x * 0 -> = null –null * 0 -> = null Same goes for >, <, !=, …

64 Nulls in Aggregation Functions count(A): counts non-null As. Returns 0 if all As are null sum(A), avg(A), min(A), max(A) –ignore null values of A –if A only contains null value, the result is null count(*): counts ALL rows (even rows that are all null values)

65 SELECT S.sname, R.bid FROM Sailors S, Reserves R WHERE S.sid = R.sid(+) We want the sailors that have not reserved a boat to appear in the result as well Sailors who have not reserved a boat will have null in the R.bid column