SQL II.

Slides:



Advertisements
Similar presentations
SQL: The Query Language Part 1 R &G - Chapter 5 Life is just a bowl of queries. -Anon (not Forrest Gump)
Advertisements

1 Advanced SQL Queries. 2 Example Tables Used Reserves sidbidday /10/04 11/12/04 Sailors sidsnameratingage Dustin Lubber Rusty.
1 Database Systems ( 資料庫系統 ) October 22/24, 2007 Lecture #5.
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.
SQL.
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
SQL (2).
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.
SQL Review.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5.
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.
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.
SQL (DML) II. Review: Formal Semantics of SQL: RA* SELECT A1, A2, …, An FROM r1, r2, …, rm WHERE P Query: Semantics:  * A1, A2,..., An (  * P (r1 x*
1 The Oracle Database System Querying the Data Database Course The Hebrew University of Jerusalem.
1 SQL: Structured Query Language Chapter 5. 2 SQL and Relational Calculus relationalcalculusAlthough relational algebra is useful in the analysis of query.
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.
Relational Algebra. Relational Query Languages n Query = “retrieval program” n Language examples: ù Theoretical : 1. Relational Algebra 2. Relational.
1 Advanced SQL. 2 Consider the following relations: –pupil (pupil_name, address, class, birthyear) –subject (subject_name, class, teacher) –grades (pupil_name,
SQL I. SQL – Introduction  Standard DML/DDL for relational DB’s  DML = “Data Manipulation Language” (queries, updates)  DDL = “Data Definition Language”
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.
SQL – Introduction  Standard DML/DDL for relational DB’s  DML = “Data Manipulation Language” (queries, updates)  DDL = “Data Definition Language” (create.
CS 370 Database Systems Lecture 12 Introduction to SQL.
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.
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.
More SQL Today:  Nested Queries  More SQL Nested Queries in SQL  Queries containing other queries  Inner query:  Can appear in FROM or WHERE clause.
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.
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 CS 186, Spring 2007, Lecture 7 R&G, Chapter 5 Mary Roth   The important thing is not to stop questioning. Albert Einstein Life is just a bowl of.
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.
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 (資料庫系統)
Basic SQL Lecture 6 Fall
SQL: Queries, Constraints, Triggers
Database Applications (15-415) SQL-Part II Lecture 9, February 04, 2018 Mohammad Hammoud.
CS 405G: Introduction to Database Systems
SQL: Queries, Constraints, Triggers
Relational Calculus.
SQL: Structured Query Language
SQL: Queries, Programming, Triggers
Presentation transcript:

SQL II

More SQL Today: Nested Queries More SQL

Nested Queries in SQL Queries containing other queries Inner query: Can appear in FROM or WHERE clause “outer query” “inner query” Example: SELECT cname FROM borrower WHERE cname IN (SELECT cname FROM depositor) think this as a function that returns the result of the inner query

Nested Queries in SQL Another example: SELECT DISTINCT cname borrower (cname, lno) account (acct_no, bname, bal) loan (lno, bname, amount) depositor (cname, acct_no) Another example: SELECT DISTINCT cname FROM borrower as b, loan as l WHERE b.lno = l.lno AND bname = “Central” AND (bname, cname) IN ( SELECT bname, cname FROM depositor as d, account as a WHERE d.acct_no = a.acct_no) Q: Describe what this query returns Ans: Names of borrowers at the Central branch who also have savings account at the same branch

Nested Queries in SQL Another example: Schema: Boats(bid, bname, color) Sailors(sid, sname, rating, age) Reserves( sid, bid, day) SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.sid = 103) Q: Describe what this query returns! Q: What happens if I replace IN with NOT IN?

Nested Queries in SQL What can we do with queries in the WHERE clause? Let A = SELECT ... FROM ... WHERE .... WHERE <expr> IN A WHERE <expr> NOT IN A WHERE <expr> < ANY (A) ( ) WHERE <expr> < ALL (A) ( ) Also (‘>’, ‘<=‘, ‘>=‘, ‘=‘, ...) WHERE EXISTS(A) ( ) WHERE UNIQUE(A)

Nested Queries in SQL ANY ( ): (or SOME) 5 6 5 5 5 (= any)  in e < ANY(A)  5 6 (5< any ) = true (read: 5 < some tuple in the relation) (5< any ) = false 5 (5 = any ) = true 5 (5  any ) = true (since 0  5) 5 (= any)  in However, ( any)  not in example: (3  any ) 3 5

Nested Queries in SQL Example query with ANY: SELECT bname FROM branch WHERE assets > ANY ( SELECT assets FROM branch WHERE bcity=‘Bkln’) Q: Describe what this query returns Ans: Find all branches that have grater assets than some branch in Brooklyn.

Nested Queries in SQL Optimization of queries! SELECT bname FROM branch WHERE assets > ANY ( SELECT assets FROM branch WHERE bcity=‘Bkln’) Q: Can you rewrite this query to something that is equivalent, but more efficient to execute? 1) SELECT assets 2) SELECT bname INTO Temp FROM branch FROM branch WHERE assets > ANY (Temp) WHERE bname=‘Bkln’ Q: Why this is better ?

Nested Queries in SQL ALL ( ): 5 6 6 10 4 5 4 6 ( all)  not in e < ALL (A)  5 6 (5< all ) = false 6 (5< all ) = true 10 4 (5 = all ) = false 5 4 (5  all ) = true (since 5  4 and 5  6) 6 ( all)  not in However, (= all)  in

Nested Queries in SQL Example query with ALL: SELECT bname FROM branch borrower (cname, lno) account (acct_no, bname, bal) loan (lno, bname, amount) depositor (cname, acct_no) Example query with ALL: SELECT bname FROM branch WHERE assets > ALL ( SELECT assets FROM branch WHERE bcity=‘Bkln’) Returns: branches that have greater assets than all branches in Brooklyn

Nested Queries in SQL Correlated Queries: when the inner query contains tuple variables of the outer query Example: Find all accounts located at branches that also hold a loan for a smaller amount SELECT DISTINCT A.cct_no FROM account as A WHERE EXISTS ( SELECT * FROM loan as L WHERE A.bname = L.bname AND A.balance > L.amt) “correlation”: inner query contains reference to table in outer query

Nested Queries with Correlation Names of sailors who have reserved boat # 103: SELECT S.sname FROM Sailors S WHERE EXISTS (SELECT * FROM Reserves R WHERE R.bid = 103 AND S.sid = R.sid)

Nested Queries in SQL EXISTS: EXISTS(A)  (i.e., true if A is not empty) Example: Find all depositors who have accounts at all branches in Brooklyn SELECT DISTINCT cname FROM depositor as S WHERE NOT EXISTS ( ( SELECT bname FROM branch WHERE bcity = ‘Bkln’) EXCEPT ( SELECT bname FROM depositor as T, account as R WHERE T.acct_no = R.acct_no AND S.cname = T.cname)) Inner Query: (branches in Brooklyn) - (branches where S has an account) Example: Find the sailors who have reserved all boats (p.150)

Find the sailors who have 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)) All boat bids – bids of boats reserved by Sailor s

Division in SQL Find names of sailors who’ve reserved all boats. Another approach: Example in book, not using EXCEPT: 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)) Sailors S such that ... there is no boat B that doesn’t have ... a Reserves tuple showing S reserved B

Sailors who have reserved all boats sid sname rating age 1 Frodo 7 22 2 Bilbo 39 3 Sam 8 27 SELECT S.name FROM Sailors S, reserves R WHERE S.sid = R.sid GROUP BY S.name, S.sid HAVING COUNT(DISTINCT R.bid) = ( Select COUNT (*) FROM Boats) Boats bid bname color 101 Nina red 102 Pinta blue 103 Santa Maria sname sid bid Frodo 1 102 Bilbo 2 101 103 Reserves sname sid count Frodo 1 Bilbo 2 3 count 3 sid bid day 1 102 9/12 2 101 9/14 9/10 103 9/13 sname sid bid Frodo 1 102,102 Bilbo 2 101, 102, 103

Nested Queries in SQL UNIQUE: UNIQUE(A) = true, if A has no duplicates Example: Find all customers who have no more than one account at “Kenmore” SELECT T.cname FROM depositor as T WHERE UNIQUE( SELECT R.cname FROM account as A, depositor as R WHERE T.cname = R.cname AND R.acct_no = A.acct_no AND A.bname = “Kenmore”) account (acct_no, bname, bal) depositor (cname, acct_no) Inner Query: Returns T’s cname for every acct held by T at Kenmore

Nested Queries in SQL Nesting also possible in FROM clause Example: Another way to express HAVING SELECT bname, avg(balance) as avgbal FROM account GROUP BY bname HAVING AVG(balance) > 1200 SELECT * FROM (SELECT bname, AVG(balance) as avgbal FROM account GOUP BY bname) AS TempRes WHERE avgbal > 1200

Nested Queries in SQL Nested query in FROM clause, another example: Find the maximum total balance across all branches SELECT MAX(tot-balance) FROM (SELECT bname, SUM(balance) FROM account GROUP BY bname) AS branch-total(bname, tot-balance)

More SQL Examples (from the book)… Find the sailors with the highest rating (p. 152) Find the name and age of the oldest sailor(s) (p. 152) Find the rating for which the average age of sailors is the minimum over all ratings (p. 162) Schema: Boats(bid, bname, color) Sailors(sid, sname, rating, age) Reserves( sid, bid, day)

Examples: Find names of sailors with the highest rating: SELECT S.sname FROM Sailors S WHERE S.rating = (SELECT MAX(S2.rating) FROM Sailors S2) Find the name and age of the oldest sailor(s) SELECT S.sname, S.age FROM Sailors S WHERE S.age = (SELECT MAX(S2.age) FROM Sailors S2)

Find the rating for which the average age of sailors is the minimum over all ratings : 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 MAX(Temp.avgage) FROM Temp)