Basic form of SQL Queries

Similar documents
Introduction to Data Management. Lecture 14 (SQL: the Saga Continues...)

SQL: Queries, Programming, Triggers

SQL: Queries, Constraints, Triggers

Introduction to Data Management. Lecture #14 (Relational Languages IV)

SQL. Chapter 5 FROM WHERE

CIS 330: Applied Database Systems

Database Systems. October 12, 2011 Lecture #5. Possessed Hands (U. of Tokyo)

Database Systems ( 資料庫系統 )

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

Introduction to Data Management. Lecture #13 (Relational Calculus, Continued) It s time for another installment of...

Lecture 3 More SQL. Instructor: Sudeepa Roy. CompSci 516: Database Systems

Database Management Systems. Chapter 5

Database Applications (15-415)

Lecture 3 SQL - 2. Today s topic. Recap: Lecture 2. Basic SQL Query. Conceptual Evaluation Strategy 9/3/17. Instructor: Sudeepa Roy

The Database Language SQL (i)

Lecture 2 SQL. Instructor: Sudeepa Roy. CompSci 516: Data Intensive Computing Systems

SQL Part 2. Kathleen Durant PhD Northeastern University CS3200 Lesson 6

SQL: The Query Language Part 1. Relational Query Languages

Enterprise Database Systems

QUERIES, PROGRAMMING, TRIGGERS

The SQL Query Language. Creating Relations in SQL. Adding and Deleting Tuples. Destroying and Alterating Relations. Conceptual Evaluation Strategy

Keys, SQL, and Views CMPSCI 645

SQL - Lecture 3 (Aggregation, etc.)

Overview of DB & IR. ICS 624 Spring Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa

This lecture. Step 1

Review: Where have we been?

Relational Calculus. Chapter Comp 521 Files and Databases Fall

Database Applications (15-415)

Introduction to Data Management. Lecture #10 (Relational Calculus, Continued)

Experimenting with bags (tables and query answers with duplicate rows):

Relational Calculus. Chapter Comp 521 Files and Databases Fall

CompSci 516 Data Intensive Computing Systems

Databases - Relational Algebra. (GF Royle, N Spadaccini ) Databases - Relational Algebra 1 / 24

This lecture. Projection. Relational Algebra. Suppose we have a relation

SQL: Queries, Programming, Triggers

Database Applications (15-415)

Lecture 2 SQL. Announcements. Recap: Lecture 1. Today s topic. Semi-structured Data and XML. XML: an overview 8/30/17. Instructor: Sudeepa Roy

Data Science 100. Databases Part 2 (The SQL) Slides by: Joseph E. Gonzalez & Joseph Hellerstein,

Relational Algebra 1

More on SQL Nested Queries Aggregate operators and Nulls

Announcements If you are enrolled to the class, but have not received the from Piazza, please send me an . Recap: Lecture 1.

CompSci 516: Database Systems

Database Systems. Announcement. December 13/14, 2006 Lecture #10. Assignment #4 is due next week.

CAS CS 460/660 Introduction to Database Systems. Relational Algebra 1.1

Data Science 100 Databases Part 2 (The SQL) Previously. How do you interact with a database? 2/22/18. Database Management Systems

ATYPICAL RELATIONAL QUERY OPTIMIZER

CSE 444: Database Internals. Section 4: Query Optimizer

RELATIONAL ALGEBRA AND CALCULUS

CSIT5300: Advanced Database Systems

Relational Query Languages. Relational Algebra. Preliminaries. Formal Relational Query Languages. Relational Algebra: 5 Basic Operations

Database Systems. Course Administration. 10/13/2010 Lecture #4

Relational Algebra. Relational Query Languages

!-%/ -%& "-!&"!!!*0**

Today s topics. Null Values. Nulls and Views in SQL. Standard Boolean 2-valued logic 9/5/17. 2-valued logic does not work for nulls

Relational Query Optimization. Highlights of System R Optimizer

Overview of Query Processing

SQL: The Query Language (Part 1)

HW1 is due tonight HW2 groups are assigned. Outline today: - nested queries and witnesses - We start with a detailed example! - outer joins, nulls?

Overview of Query Evaluation. Overview of Query Evaluation

CompSci 516 Database Systems. Lecture 2 SQL. Instructor: Sudeepa Roy

Database Management Systems. Chapter 5

CS330. Query Processing

Relational Algebra 1. Week 4

Implementation of Relational Operations

CS 4604: Introduc0on to Database Management Systems. B. Aditya Prakash Lecture #3: SQL and Rela2onal Algebra- - - Part 1

Database Management Systems. Chapter 4. Relational Algebra. Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1

Evaluation of relational operations

CSE 444: Database Internals. Sec2on 4: Query Op2mizer

Evaluation of Relational Operations. Relational Operations

Relational Algebra Homework 0 Due Tonight, 5pm! R & G, Chapter 4 Room Swap for Tuesday Discussion Section Homework 1 will be posted Tomorrow

Relational Algebra. [R&G] Chapter 4, Part A CS4320 1

Relational Algebra. Note: Slides are posted on the class website, protected by a password written on the board

CSCC43H: Introduction to Databases. Lecture 3

Overview of Implementing Relational Operators and Query Evaluation

Overview of Query Evaluation

Evaluation of Relational Operations

CAS CS 460/660 Introduction to Database Systems. Query Evaluation II 1.1

CS 186, Fall 2002, Lecture 8 R&G, Chapter 4. Ronald Graham Elements of Ramsey Theory

3. User Interfaces and SQL Language*

Query Optimization. Schema for Examples. Motivating Example. Similar to old schema; rname added for variations. Reserves: Sailors:

Rewrite INTERSECT using IN

Implementation of Relational Operations. Introduction. CS 186, Fall 2002, Lecture 19 R&G - Chapter 12

v Conceptual Design: ER model v Logical Design: ER to relational model v Querying and manipulating data

CSEN 501 CSEN501 - Databases I

Relational Query Languages

Midterm Exam #2 (Version A) CS 122A Winter 2017

Evaluation of Relational Operations

Database Management Systems. Chapter 5

Relational Query Optimization

Administriva. CS 133: Databases. General Themes. Goals for Today. Fall 2018 Lec 11 10/11 Query Evaluation Prof. Beth Trushkowsky

Advanced Database Management Systems

Announcement. Reading Material. Overview of Query Evaluation. Overview of Query Evaluation. Overview of Query Evaluation 9/26/17

SQL: Queries, Constraints, Triggers (iii)

Operator Implementation Wrap-Up Query Optimization

An SQL query is parsed into a collection of query blocks optimize one block at a time. Nested blocks are usually treated as calls to a subroutine

HW2 out! Administrative Notes

Query Optimization. Schema for Examples. Motivating Example. Similar to old schema; rname added for variations. Reserves: Sailors:

SQL SQL SQL SQL SQL SQL SQL. Eugene Wu Fall 2018

Relational Algebra. Chapter 4, Part A. Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1

Advanced Database Management Systems

Transcription:

SQL - 1 Week 6

Basic form of SQL Queries SELECT FROM WHERE target-list relation-list qualification target-list A list of attributes of output relations in relation-list relation-list A list of relation names (possibly with a range-variable after each name) e.g. Sailors S, Reserves R qualification Comparisons (Attr op const or Attr1 op Attr2, where op is one of <, >,,, =, ) combined using AND, OR and NOT. 2

What s contained in an SQL Query? SELECT FROM WHERE target-list relation-list qualification Every SQL Query must have: SELECT clause: specifies columns to be retained in result FROM clause: specifies a cross-product of tables The WHERE clause (optional) specifies selection conditions on the tables mentioned in the FROM clause 3

General SQL 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. 4

Conceptual Evaluation Strategy Nested loops evaluation: target-attribute-list SELECT Foreach tuple t1 in R1 FROM R1,, Rn WHERE 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 end qualification 5

Table Definitions We will be using the following relations in our examples: Sailors(sid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day) 6

Sailors sid sname rating age 22 Dustin 7 45.0 29 Brutus 1 33.0 31 Lubber 8 55.5 32 Andy 8 25.5 58 Rusty 10 35.0 64 Horatio 7 35.0 71 Zorba 10 16.0 74 Horatio 9 35.0 85 Art 3 25.5 95 Bob 3 63.5 Reserves sid bid day 22 101 10/10/04 22 102 10/10/04 22 103 10/08/04 22 104 10/07/04 31 102 11/10/04 31 103 11/06/04 31 104 11/12/04 64 101 09/05/04 64 102 09/08/04 74 103 09/08/04 bid bname Color Boats 101 Interlake blue 102 Interlake red 103 Clipper green 104 Marine red 7

A Simple SQL Query Find the names and ages of all sailors sid sname rating age 22 Dustin 7 45.0 29 Brutus 1 33.0 31 Lubber 8 55.5 32 Andy 8 25.5 58 Rusty 10 35.0 64 Horatio 7 35.0 71 Zorba 10 16.0 74 Horatio 9 35.0 85 Art 3 25.5 95 Bob 3 63.5 8

Result of Previous Query sname age Dustin 45.0 Brutus 33.0 Lubber 55.5 Andy 25.5 Rusty 35.0 Horatio 35.0 Zorba 16.0 Horatio 35.0 Art 25.5 Bob 63.5 SELECT S.sname, S.age FROM Sailors S; Duplicate Results 9

Preventing Duplicate Tuples in the Result Use the DISTINCT keyword in the SELECT clause: SELECT DISTINCT S.sname, S.age FROM Sailors S; 10

Results of Original Query without Duplicates sname age Dustin 45.0 Brutus 33.0 Lubber 55.5 Andy 25.5 Rusty 35.0 Horatio 35.0 Zorba 16.0 Art 25.5 Bob 63.5 Appears only once 11

Example SQL Query 1 Find the names of sailors who have reserved boat 103 Relational Algebra: π sname ((σ bid=103 Reserves) Sailors) SQL: SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103; 12

Result of Previous Query sid bid day 22 103 10/08/04 31 103 11/06/04 74 103 09/08/04 Result: sname Dustin Lubber Horatio sid sname rating age 22 Dustin 7 45.0 29 Brutus 1 33.0 31 Lubber 8 55.5 32 Andy 8 25.5 58 Rusty 10 35.0 64 Horatio 7 35.0 71 Zorba 10 16.0 74 Horatio 9 35.0 85 Art 3 25.5 95 Bob 3 63.5 13

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 R.bid=103; However, it is a good OR style to always use range variables! SELECT sname FROM Sailors, Reserves WHERE Sailors.sid=Reserves.sid AND bid=103; 14

Example SQL Query 2 Find the sids of sailors who have reserved a red boat 15

Example SQL Query 3 Find the names of sailors who have reserved a red boat 16

Example SQL Query 4 Find the colors of boats reserved by Lubber 17

Example SQL Query 5 Find the names of sailors who have reserved at least one boat 18

Expressions and Strings AS and = are two ways to name fields in result. LIKE is used for string matching. _ stands for exactly one arbitrary character and % stands for 0 or more arbitrary characters. 19

Expressions and Strings Example Find triples (of ages of sailors and two fields defined by expressions, i.e. current age-1 and twice the current age) for sailors whose names begin and end with B and contain at least three characters. SELECT S.age, age1=s.age-1, 2*S.age AS age2 FROM Sailors S WHERE S.sname LIKE B_%B ; sid sname rating age 22 Dustin 7 45.0 29 Brutus 1 33.0 31 32 58 Lubber Andy Rusty 8 8 10 55.5 25.5 35.0 Result: 64 71 74 85 95 Horatio Zorba Horatio Art Bob 7 10 9 3 3 35.0 16.0 35.0 25.5 63.5 age age1 age2 63.5 62.5 127.0 20

UNION, INTERSECT, EXCEPT UNION: Can be used to compute the union of any two union-compatible sets of tuples (which are themselves the result of SQL queries). EXCEPT: Can be used to compute the setdifference operation on two union-compatible sets of tuples (Note: In ORACLE, the command for set-difference is MINUS). INTERSECT: Can be used to compute the intersection of any two union-compatible sets of tuples. 21

Illustration of UNION 1 Find the names of sailors who have reserved a red or a green boat Intuitively, we would write: SELECT S.sname 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 ); 22

Illustration of UNION 2 We can also do this using a UNION keyword: SELECT S.sname FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color= red UNION SELECT S.sname FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color= green ; Unlike other operations, UNION eliminates duplicates! Same as INTERSECT, EXCEPT. To retain duplicates, use UNION ALL 23

Illustration of INTERSECT 1 Find names of sailors who ve reserved a red and a green boat Intuitively, we would write the SQL query as: SELECT S.sname 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 ); 24

Illustration of INTERSECT 2 We can also do this using a INTERSECT keyword: SELECT S.sname FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color= red INTERSECT SELECT S2.sname FROM Sailors S2, Boats B2, Reserves R2 WHERE S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color= green ; (Is this correct??) 25

(Semi-)Correct SQL Query for the Previous Example 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 S2.sid FROM Sailors S2, Boats B2, Reserves R2 WHERE S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color= green ; (This time we have actually extracted the sids of sailors, and not their names.) (But the query asks for the names of the sailors.) 26

Illustration of EXCEPT Find the sids of all sailors who have reserved red boats but not green boats: 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 S2.sid FROM Sailors S2, Boats B2, Reserves R2 WHERE S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color= green ; Use MINUS instead of EXCEPT in Oracle 27

Nested Queries A nested query is a query that has another query embedded within it; this embedded query is called the subquery. Subqueries generally occur within the WHERE clause (but can also appear within the FROM and HAVING clauses) Nested queries are a very powerful feature of SQL. They help us write short and efficient queries. (Think of nested for loops in C++. Nested queries in SQL are similar) 28

Nested Query 1 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); 29

Nested Query 2 Find names of sailors who have 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 ) 30

Nested Query 3 Find the names of sailors who have reserved a red boat SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid IN (SELECT B.bid FROM Boats B WHERE B.color = red )); What about Find the names of sailors who have NOT reserved a red boat? 31

Revisit a previous query Find names of sailors who ve reserved 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 INTERSECT SELECT S2.sid FROM Sailors S2, Boats B2, Reserves R2 WHERE S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color= green ; 32

Revisit a previous query Find names of sailors who ve reserved a red and a green boat SELECT S.sname FROM Sailor S WHERE S.sid IN (SELECT R.sid FROM Boats B, Reserves R WHERE R.bid=B.bid AND B.color= red INTERSECT SELECT R2.sid FROM Boats B2, Reserves R2 WHERE R2.bid=B2.bid AND B2.color= green ); 34

Correlated Nested Queries 1 Thus far, we have seen nested queries where the inner subquery is independent of the outer query. We can make the inner subquery depend on the outer query. This is called correlation. 35

Correlated Nested Queries 2 Find names of sailors who have reserved boat 103 SELECT S.sname FROM Sailors S WHERE EXISTS (SELECT * FROM Reserves R Tests whether the set is nonempty. If it is, then return TRUE. WHERE R.bid=103 AND R.sid=S.sid); (For finding sailors who have not reserved boat 103, we would use NOT EXISTS) 36

ANY and ALL operators Find sailors whose rating is better than some sailor named Horatio SELECT S.sid FROM Sailors S WHERE S.rating > ANY (SELECT S2.rating FROM Sailors S2 WHERE S2.sname= Horatio ); (Can you find the probable bug in this SQL query??) Hint: what if there are several sailors named Horatio? 38

Using ALL operator Find sailors whose rating is better than every sailor named Horatio SELECT S.sid FROM Sailors S WHERE S.rating > ALL(SELECT S2.rating FROM Sailors S2 WHERE S2.sname= Horatio ); 39

Aggregate operators What is aggregation? Computing arithmetic expressions, such as Minimum or Maximum The aggregate operators supported by SQL are: COUNT, SUM, AVG, MIN, MAX 40

Aggregate Operators COUNT(A): The number of values in the column A SUM(A): The sum of all values in column A AVG(A): The average of all values in column A MAX(A): The maximum value in column A MIN(A): The minimum value in column A (We can use DISTINCT with COUNT, SUM and AVG to compute only over non-duplicated columns) 41

Using the COUNT operator Count the number of sailors SELECT COUNT (*) FROM Sailors S; 42

Example of SUM operator Find the sum of ages of all sailors with a rating of 10 SELECT SUM (S.age) FROM Sailors S WHERE S.rating=10; 43

Example of AVG operator Find the average age of all sailors with rating 10 SELECT AVG (S.age) FROM Sailors S WHERE S.rating=10; 44

Example of MAX operator Find the name and age of the oldest sailor SELECT S.sname, MAX(S.age) FROM Sailors S; But this is illegal in SQL!! 45

Correct SQL Query for MAX SELECT S.sname, S.age FROM Sailors S WHERE S.age = ( SELECT MAX(S2.age) FROM Sailors S2 ); 46

Another Aggregate Query Count the number of different sailors SELECT COUNT (DISTINCT S.sname) FROM Sailors S 47

More to come BETWEEN AND Advanced SQL concepts : GROUP BY ORDER BY HAVING 48