SQL Part I: Standard Queries. COMP-421: Database Systems - SQL Queries I 2 Example Instances sid sname rating age 22 debby 7 35 31 debby 8 55 58 lilly.

Slides:



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

Winter 2002Arthur Keller – CS 1806–1 Schedule Today: Jan. 22 (T) u SQL Queries. u Read Sections Assignment 2 due. Jan. 24 (TH) u Subqueries, Grouping.
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.
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 and Relational Algebra Zaki Malik September 02, 2008.
SQL.
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.
SQL Review.
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.
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 Table Alteration. 2 Altering Tables Table definition can be altered after its creation –Adding columns –Changing columns’ definition –Dropping columns.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
1 Chapter 5 SQL: QUERIES, CONSTRAINTS, TRIGGERS. 2 INTRODUCTION - The current presentation is consistent with both SQL-92 and SQL: 99 (differences will.
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.
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.
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.
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.
Relational Algebra.
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.
The Oracle Database System. Connecting to the Database At the command line prompt, write: sqlplus In the beginning your password.
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.
SQL: The Query Language Part 1 R&G - Chapter 5 1.
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.
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.
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
Basic SQL Lecture 6 Fall
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: Queries, Programming, Triggers
SQL: Queries, Programming, Triggers
Presentation transcript:

SQL Part I: Standard Queries

COMP-421: Database Systems - SQL Queries I 2 Example Instances sid sname rating age 22 debby debby lilly Sailors Reserves R S sid bid day /24/ /07/ /07/ /07/31 bid bname color 101Interlake green 103 Snapper red Boat B

COMP-421: Database Systems - SQL Queries I 3 Principle Form of a Query q SELECT desired attributes FROM list of relations WHERE qualification ( where clause is optional) q SELECT rating,age FROM Sailors WHERE rating <= 6 OR age < 40 q Operational Semantics I Imagine a tuple variable ranging over all tuples of the relation  For each tuple: check if is satisfies the WHERE clause. If so, print the attributes in SELECT. q Conversion to Relational Algebra   rating,age (  rating<=6  age<40 (Sailors))  Start with the relation in the FROM clause  Apply , using condition in WHERE clause (selection)  Apply ∏, using attributes in SELECT clause (projection) I Difference: duplicates not eliminated sid sname rating age 22 debby debby lilly ratingage

COMP-421: Database Systems - SQL Queries I 4 The WHERE Clause q Comparison:  attr1 op const, or  attr1 op attr2,  op is one of , , , , , , LIKE I We may apply the usual arithmetic operations +, *, etc. to numeric values before we compare  Qualification/Condition: Comparisons combined using AND, OR and NOT I name =‘Cheng’ AND NOT age = 18  name LIKE ‘%e_g’ (%: any string, _:any character)  Further string operations, e.g., concatenation, string-length, etc. q As default for most statements, SQL uses ‘multiset’ semantic, i.e., duplicates are allowed and not eliminated (as long as they do not violate a primary key / unique constraint)  DISTINCT is an optional keyword indicating that the answer should not contain duplicates.

COMP-421: Database Systems - SQL Queries I 5 Attribute Lists q Distinct SELECT DISTINCT sname FROM Sailors ( no WHERE clause OK) q Star as list of all attributes SELECT * FROM Sailors WHERE rating < 9 q Renaming columns SELECT sid, sname AS sailor FROM Sailors WHERE rating < 9 sid sname rating age 22 debby debby 8 55 sailor 22 debby 31 debby sname debby lilly sid sname rating age 22 debby debby lilly 10 35

COMP-421: Database Systems - SQL Queries I 6 Attribute Lists (contd) q Expressions as values in columns SELECT sname, rating+1 AS upgrade FROM Sailors q Constants as attribute values SELECT rating AS reality, ‘10’ AS dream FROM Sailors WHERE sname LIKE ‘_e%y’ q Ordered Output SELECT * FROM Sailors ORDER BY age,rating sname upgrade debby 8 debby 9 lilly 11 reality dream sid sname rating age 22 debby lilly debby 8 55

COMP-421: Database Systems - SQL Queries I 7 Multirelational Queries  List of relations in FROM clause q Relation-dot-attribute disambiguates attributes from several relations. q Cross-Product: SELECT * FROM Sailors, Reserves Sailors X Reserves q Join: I Have to indicate comparison even with natural join I Example: “give me the names of all sailors that have reserved boat #103” SELECT sname FROM Sailors, Reserves WHERE Sailors.sid = Reserves.sid AND bid = 103  sname (  bid=103 (Reserves) Sailors)

COMP-421: Database Systems - SQL Queries I 8 Semantics q Conversion to Relational Algebra  Same as for single relation, but start with the product (X) of all the relations mentioned in the FROM clause q Parallel assignment of tuple variables  Consider a tuple variable for each relation in the FROM I Consider all possible assignments  For each such assignment of tuple variables to tuples that makes the WHERE true, output the attributes of the SELECT sid sname rating age 22 debby debby lilly sid bid day /24/ /07/ /07/ /07/31 sname debby Lilly lilly

COMP-421: Database Systems - SQL Queries I 9 Semantics (contd). q Nested Loop Assignment LET the tuple variables in the from clause range over relations R1, R2, …., Rn FOR each tuple t1 in relation R1 DO FOR each tuple t2 in relation R2 DO … FOR each tuple tn in relation Rn DO If the where clause is satisfied when the values from t1, t2, … tn are substituted for all attribute references THEN evaluate the attributes of the select clause according to t1, t2, …. tn and produce the tuple of values that results.

COMP-421: Database Systems - SQL Queries I 10 Range Variables  Optional use of range variables SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid = R.sid AND R.bid = 103 q Use of range variable required when the same relation appears twice in the FROM clause q Example: “find pairs of sailors that have rented the same boat” SELECT r1.sid, r2.sid FROM Reserves r1, Reserves r2 WHERE r1.bid = r2.bid AND r1.sid < r2.sid (note that r1.sid < r2.sid is needed to avoid producing (58,58) and to avoid producing a pair in both directions.

COMP-421: Database Systems - SQL Queries I 11 Union, Intersection, Difference q Input relations for set operators must be set-compatible, I.e. they must have I Same number of attributes I The attributes, taken in order, must have same type q As default, result relation is a set!!! (no multiset) q Many systems do not provide primitives for intersection and difference

COMP-421: Database Systems - SQL Queries I 12 Union q Sailors(sid,sname,rating,age) Reserves(sid,bid,day) Boats(bid,bname,color) q Find sailors that have reserved a red or a green boat SELECT R.sid FROM Reserves R, Boats B WHERE R.bid = B.bid AND (B.color = ‘red’ OR B.color = ‘green’) SELECT R.sid FROM Reserves R, Boats B WHERE R.bid = B.bid AND B.color = ‘red’ UNION SELECT R.sid FROM Reserves R, Boats B WHERE R.bid = B.bid AND B.color = ‘green’

COMP-421: Database Systems - SQL Queries I 13 Intersection q Find sailors that have reserved a red and a green boat (1) SELECT R.sid FROM Reserves R, Boats B WHERE R.bid = B.bid AND B.color = ‘red’ INTERSECT SELECT R.sid FROM Reserves R, Boats B WHERE R.bid = B.bid AND B.color = ‘green’ (2) SELECT R1.sid FROM Reserves R1, Reserves R2, Boats B1, Boats B2 WHERE (R1.bid = B1.bid AND B1.color = ‘red’) AND (R2.bid = B2.bid AND B2.color = ‘green’) AND R1.sid = R2.sid) sid bid day /24/ /07/ /07/ /07/31 sid bid day /24/ /07/ /07/ /07/31 bid color 101 green 103 red bid color 101 green 103 red

COMP-421: Database Systems - SQL Queries I 14 Difference q Find sailors that have reserved a red but not a green boat SELECT R.sid FROM Reserves R, Boats B WHERE R.bid = B.bid AND B.color = ‘red’ EXCEPT ( Oracle: MINUS) SELECT R.sid FROM Reserves R, Boats B WHERE R.bid = B.bid AND B.color = ‘green’

COMP-421: Database Systems - SQL Queries I 15 Multiset Semantic q A multiset (bag) may contain the same tuple more than once, although there is no specified order (unlike a list). I Example: {1, 2, 1, 3} is a multiset, but not a set q Multiset Union: I Sum the times an element appears in the two multisets I Example: {1, 2, 2}  {1, 2, 3, 3} = {1, 1, 2, 2, 2, 3, 3} q Multiset Intersection: I Take the minimum of the number of occurrences in each multiset. I Example: {1, 2, 2}  {1, 1, 2, 2, 3, 3} = {1, 2,2} q Multiset Difference: I Subtract the number of occurrences in the two multisets I Examples: {1, 2, 2} - {1, 2, 3, 3} = {2} q Some familiar laws for sets also hold for multisets (e.g., union is commutative); but other laws do not hold (e.g., R  (S  T)  (R  S)  (R  T)

COMP-421: Database Systems - SQL Queries I 16 Multiset Semantic in SQL q Although SQL generally works with multisets, it uses set semantic for union/intersection/difference q To enforce multiset semantic for these operators use I UNION ALL, INTERSECT ALL, EXCEPT ALL SELECT R.sid FROM Reserves R, Boats B WHERE R.bid = B.bid AND B.color = ‘red’ UNION ALL SELECT R.sid FROM Reserves R, Boats B WHERE R.bid = B.bid AND B.color = ‘green’

COMP-421: Database Systems - SQL Queries I 17 Nested queries: The IN operator q A where clause can itself contain an SQL query. The inner query is called a subquery q Find names of sailors who have reserved boat #103 SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid = 103)  To find sailors who have NOT reserved boat #103 use NOT IN q Semantics best understood by nested loop assignment q Multiple attributes: I WHERE (a1,a2) IN (SELECT a3, a4…

COMP-421: Database Systems - SQL Queries I 18 Exists Operator  EXISTS ( relation) is true iff the relation is non-empty q Find 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 R.sid = S.sid) q Scoping rule: to refer to outer Sailors in the inner subquery, we need to give a range variable to the outer relation. q A subquery that refers to values from a surrounding query is called a correlated subquery. q Since the inner query depends on the row of the outer query it must be reevaluated for each row in the outer query

COMP-421: Database Systems - SQL Queries I 19 Quantifiers  ANY and ALL behave as existential and universal quantifiers, respectively. q Syntax I WHERE attr op ANY (SELECT … I WHERE attr op ALL (SELECT  op is one of , , , , ,  q Find the sailors with the highest rating SELECT * FROM Sailors WHERE rating  ALL (SELECT rating FROM Sailors)

COMP-421: Database Systems - SQL Queries I 20 Complex queries (Division) q Find sailors who have reserved all boats SELECT 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)) SELECT 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))