Basic SQL Lecture 6 Fall 2008 1.

Slides:



Advertisements
Similar presentations
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5 Modified by Donghui Zhang.
Advertisements

Introduction to Database Systems 1 SQL: The Query Language Relation Model : Topic 4.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5.
1 Lecture 11: Basic SQL, Integrity constraints
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.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5.
CS 405G: Introduction to Database Systems
CMPT 258 Database Systems SQL: Queries, Constraints, Triggers (Chapter 5) Part II home.manhattan.edu/~tina.tian.
1 Today’s Class  Relational Model  SQL CS F212 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.
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.
SQL: The Query Language Part 1
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
1 SQL: Structured Query Language Chapter 5. 2 SQL and Relational Calculus relationalcalculusAlthough relational algebra is useful in the analysis of query.
CSC343 – Introduction to Databases - A. Vaisman1 SQL: Queries, Programming, Triggers.
Chapter 5.  Data Manipulation Language (DML): subset of SQL which allows users to create queries and to insert, delete and modify rows.  Data Definition.
Introduction to SQL Basics; Christoph F. Eick & R. Ramakrishnan and J. Gehrke 1 Introduction to SQL Basics --- SQL in 45 Minutes Chapter 5.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L6_SQL(1) 1 SQL: Queries, Constraints, Triggers Chapter 5 – Part 1.
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,
SQL 2 Introduction Structured Query Language (SQL): the most widely used commercial relational database language Originally.
Unit 5/COMP3300/ SQL: Queries, Programming, Triggers Chapter 5.
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.
Introduction to SQL ; Christoph F. Eick & R. Ramakrishnan and J. Gehrke 1 Using SQL as a Query Language COSC 6340.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
CMPT 258 Database Systems SQL Queries (Chapter 5).
1 SQL: Queries, Constraints, Triggers Chapter 5. 2 Overview: Features of SQL  Data definition language: used to create, destroy, and modify tables and.
1 SQL: The Query Language (Part II). 2 Expressions and Strings v Illustrates use of arithmetic expressions and string pattern matching: Find triples (of.
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 1 Raghu Ramakrishnan SQL: Queries, Programming, Triggers Chpt 5 Jianping Fan.
SQL: The Query Language Part 1 R&G - Chapter 5 1.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Basic SQL Queries.
CENG 351 File Structures and Data Management1 SQL: Structured Query Language Chapter 5.
1 CS122A: Introduction to Data Management Lecture 9 SQL II: Nested Queries, Aggregation, Grouping Instructor: Chen Li.
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.
1 CS122A: Introduction to Data Management Lecture 8 Introduction to SQL Instructor: Chen Li.
SQL: The Query Language Part 1 R&G - Chapter 5 Lecture 7 The important thing is not to stop questioning. Albert Einstein.
SQL: Queries, Constraints, Triggers
Basic SQL Queries Go over example queries, like 10 > ALL.
COP Introduction to Database Structures
© פרופ' יהושע שגיב, האוניברסיטה העברית
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.
Database Systems (資料庫系統)
SQL: Queries, Constraints, Triggers
SQL: The Query Language
SQL: Queries, Programming, Triggers
CS 405G: Introduction to Database Systems
SQL: Queries, Constraints, Triggers
SQL: The Query Language Part 1
SQL: Structured Query Language
SQL: Queries, Programming, Triggers
SQL: Queries, Constraints, Triggers
SQL: Queries, Programming, Triggers
Presentation transcript:

Basic SQL Lecture 6 Fall 2008 1

Queries non expressible in Relational Algebra Find the average rating of sailors older than 30 Find the number of boats On Sailors, for each rating, find the average age We cannot express recursive closure queries 

More .. (S’(superiorSid sid),  superiorSid (sid=99 (Sailors))) Consider : Sailors (sid:integer,sname:string(20),rating:integer,age:float,superiorSid:integer) We cannot express recursive closure queries like Find all superiors of a sailor whose sid is 99. (S’(superiorSid sid),  superiorSid (sid=99 (Sailors))) (S’’(superiorSid sid),  superiorSid ((S’ Sailors))) (S’’’(superiorSid sid),  superiorSid ((S’’ Sailors)))  S’  S’’  S’’’ …. We cannot express these kinds of queries without a looping mechanism.

R1 Example Instances We will use these instances of the Sailors and Reserves relations in our examples. If the key for the Reserves relation contained only the attributes sid and bid, how would the semantics differ? S1 S2

Basic SQL Query SELECT target-list FROM relation-list WHERE qualification relation-list A list of relation names (possibly with a range-variable after each name). One name can appear more than once, with different range-variable names. target-list A list of attributes of the relations in relation-list

Basic SQL Query SELECT target-list FROM relation-list WHERE qualification qualification Comparisons (“Attr op const” or “Attr1 op Attr2”, where op is one of =, >, >=, <, <=, <>) combined using AND, OR and NOT.

Basic SQL Query: Examples SELECT S.sname FROM Sailors S WHERE S.age > 50 SELECT DISTINCT S.sname FROM Sailors S WHERE S.age > 50

Basic SQL Query SELECT [DISTINCT] target-list FROM relation-list WHERE qualification DISTINCT is an optional keyword indicating that the answer should not contain duplicates. Default is that duplicates are not eliminated!

Set vs. Bag (Multiset) Set: {1, 2, 3} Bag: {1, 2, 2, 2, 3, 3} No duplicates, no order Bag: {1, 2, 2, 2, 3, 3} Duplicate possible, no order Membership test Same SQL uses “Bag Semantics” Relational algebra uses “Set Semantics”

Basic SQL Query: Some Examples SELECT * FROM Sailors SELECT * FROM Sailors WHERE age > 50 SELECT sid FROM Sailors WHERE age > 50 SELECT S.sname FROM Sailors AS S WHERE S.age > 50 SELECT S.sname FROM Sailors S WHERE S.age > 50 SELECT DISTINCT S.sname FROM Sailors S WHERE S.age > 50 SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103

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

Conceptual Evaluation Strategy Nested loops evaluation: Foreach tuple t1 in R1 … Foreach tuple tn in Rn 1. Substitute the attribute names in the qualification part with values from t1, …, tn 2. If the modified qualification part evaluates True then output target-attribute-values else do nothing end SELECT target-attribute-list FROM R1, …, Rn WHERE qualification

Example: Conceptual Evaluation SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103

A Note on Range Variables Really needed only if the same relation appears twice in the FROM clause. The previous query can also be written as: SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND bid=103 It is good style, however, to use range variables always! SELECT sname FROM Sailors, Reserves WHERE Sailors.sid=Reserves.sid AND bid=103 OR

Find sailors (sids) who’ve reserved at least one boat SELECT S.sid FROM Sailors S, Reserves R WHERE S.sid=R.sid Is it different from algebra query below? How many times the same sid may appear? What is the effect of replacing S.sid by S.sname in the SELECT clause?

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.

Strings: LIKE and NOT LIKE LIKE (NOT LIKE) is used for string matching. SELECT S.sname, S.age FROM Sailors S WHERE S.sname LIKE ‘B%’ SELECT S.sname, S.age FROM Sailors S WHERE S.sname NOT LIKE ‘_B%’ SELECT S.sname, S.age FROM Sailors S WHERE S.sname LIKE ‘_B%’

Set Operations (back to set semantics) Select … From … Where… Set-op Where … Set-ops: All duplicates removed! Union Intersect Except (difference) Bag version Union all, Intersect all, Except all

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? Also available: EXCEPT (What do we get if we replace UNION by EXCEPT?) SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND (B.color=‘red’ 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 AND B.color=‘green’

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’) 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 B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ INTERSECT AND B.color=‘green’

Except EXCEPT: Can be used to compute the set-difference of any two union-compatible sets of tuples (which are themselves the result of SQL queries). Find sids of sailors whose rating is 10, but have not reserved boat #103 SELECT S.sid FROM Sailors S WHERE S.rating = 10 EXCEPT SELECT R.sid FROM Reserves R WHERE R.bid=103

Qualification involving Sets Value IN SET Value NOT IN SET EXISTS SET NOT EXISTS SET UNIQUE SET Value op ANY SET Value op ALL SET op is one of =, >, >=, <, <=, <> Where do we get SET from? Select statement! Nested queries.

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) A very powerful feature of SQL: a WHERE clause can itself contain an SQL query! (Actually, so can FROM and HAVING clauses.) To find sailors who’ve not reserved #103, use NOT IN. To understand semantics of nested queries, think of nested loops evaluation: For each Sailors tuple, check the qualification by computing the subquery.

22 IN FALSE This tuple is not selected 58 TRUE: This tuple is selected Instance of Sailors Instance of Reserves 31 22 IN FALSE This tuple is not selected 58 TRUE: This tuple is selected Answer SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid=103) (SELECT R.sid FROM Reserves R WHERE R.bid=103)

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. Illustrates why, in general, subquery must be re-computed for each Sailors tuple.

EXISTS : TRUE : Tuple selected FROM Reserves R Instance of Sailors Instance of Reserves 31 (SELECT * FROM Reserves R WHERE R.bid=103 AND 22 =R.sid) 58 EXISTS : TRUE : Tuple selected Answer SELECT S.sname FROM Sailors S WHERE EXISTS (SELECT * FROM Reserves R WHERE R.bid=103 AND S.sid=R.sid) EXISTS : FALSE: tuple no selected

Nested Queries with Correlation UNIQUE SET: TRUE : No duplicates tuples in the subquery or empty FALSE: Otherwise Find names of sailors who’ve reserved boat #103 at most once: SELECT S.sname FROM Sailors S WHERE UNIQUE (SELECT R.bid FROM Reserves R WHERE R.bid=103 AND S.sid=R.sid) Why do we have to use R.bid instead of * ?

More on Set-Comparison Operators Can also use NOT IN, NOT EXISTS and NOT UNIQUE: SELECT S.sname FROM Sailors S WHERE S.sid NOT IN (SELECT R.sid FROM Reserves R WHERE R.bid=103) WHERE NOT EXISTS (SELECT * WHERE R.bid=103 AND S.sid=R.sid) Find names of sailors who have not reserved boat #103 SELECT S.sname FROM Sailors S WHERE NOT UNIQUE (SELECT R.bid FROM Reserves R WHERE R.bid=103 AND S.sid=R.sid) Find sailors who have reserved boat #103 more than once

More on Set-Comparison Operators Also available: op ANY, op ALL, op is: op ANY : v op ANY (subquery) : TRUE if the value “v is op” with respect to some value retrieved by the subquery. v: attribute name or a constant

More on Set-Comparison Operators: “ANY” 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’)

More on Set-Comparison Operators op ALL: v op ALL (subquery) : TRUE if “v is op” with respect to all the values retrieved by the subquery. Find sailors whose rating is higher than all sailors called Horatio SELECT * FROM Sailors S WHERE S.rating > ALL (SELECT S2.rating FROM Sailors S2 WHERE S2.sname=‘Horatio’) Find sailors with highest rating SELECT * FROM Sailors S WHERE S.rating >= ALL (SELECT S2.rating FROM Sailors S2)

More Complex Nested Queries Find sailors who’ve have reserved a red boat SELECT * FROM Sailors S WHERE EXISTS (SELECT * FROM RESERVES R WHERE S.sid=R.sid AND EXISTS (SELECT * FROM BOATS B WHERE B.COLOR = ‘red’ AND B.bid = R.bid))

Rewriting INTERSECT Queries Using Nested Queries Find sid’s of sailors who’ve reserved both a red and a green boat: SELECT DISTINCT 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’)

Rewriting INTERSECT Queries Using Nested Queries To find names 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 DISTINCT S.sname FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ AND EXISTS (SELECT S2.sid FROM Sailors S2, Boats B2, Reserves R2 WHERE S.sid = S2.sid AND S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color=‘green’) Similarly, EXCEPT queries re-written using NOT IN/NOT EXISTS.

Division in SQL Find sailors who’ve reserved all boats. 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)) For each sailor S Subquery computes those boats that have not been reserved by the sailor S If the sailor S have reserved all boats, the result of the subquery is empty : NOT EXISTS :TRUE

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

Conclusions for now This is the “core” part of SQL Bag, nested loop Similar to Relational Algebra, but not quite A lot of extensions coming up!