Database Management Systems. Chapter 5

Similar documents
CSIT5300: Advanced Database Systems

{ } Plan#for#Today# CS#133:#Databases# RelaKonal#Calculus# Rel.#Alg.#Compound#Operator:# Division# A B = x y B( x, y A)

SQL Aggregate Queries

Comp115: Databases. Relational Algebra

RESERVATION.Sid and RESERVATION.Bid are foreign keys referring to SAILOR.Sid and BOAT.Bid, respectively.

CS 461: Database Systems. Relational Algebra. supplementary material: Database Management Systems Sec. 4.1, 4.2 class notes

RESERVATION.Sid and RESERVATION.Bid are foreign keys referring to SAILOR.Sid and BOAT.Bid, respectively.

sname rating 8 .forward Relational Algebra Operator Precedence Sample Query 0 Example Schema bid 103 sname( ( Sailors) Relational Algebra Queries

CSIT5300: Advanced Database Systems

SQL language: set operators

Using SQL in MS Access

Database Systems CSE 414

TECHNICAL NOTE HOW TO USE LOOPERS. Kalipso_TechDocs_Loopers. Revision: 1.0. Kalipso version: Date: 16/02/2017.

Couples, Relations and Functions

The Coach then sorts the 25 players into separate teams and positions

MEETPLANNER DESIGN DOCUMENT IDENTIFICATION OVERVIEW. Project Name: MeetPlanner. Project Manager: Peter Grabowski

NCSS Statistical Software

Team BUSY : Excise register RG-23 A-11, provision made to input starting S.No.

Iteration: while, for, do while, Reading Input with Sentinels and User-defined Functions

Gaia ARI. ARI s Gaia Workshop. Grégory Mantelet. 20 th June 2018 CDS / ARI

USA Jump Rope Tournament Software User Guide 2014 Edition

Applied Econometrics with. Time, Date, and Time Series Classes. Motivation. Extension 2. Motivation. Motivation

An Overview of Recent Auction Formats

Working with Object- Orientation

by Robert Gifford and Jorge Aranda University of Victoria, British Columbia, Canada

Homework 4 PLAYERS, TEAMS, MATCHES, PENALTIES, COMMITTEE_MEMBERS

Design, Operation and Maintenance of a Swimming Pool

CENTER PIVOT EVALUATION AND DESIGN

Exam Name: db2 udb v7.1 family fundamentals

SIDRA INTERSECTION 6.1 UPDATE HISTORY

Healthcare Analytics Anticoagulation Time in Therapeutic Range Calculation Documentation September 4, 2015

Oracle 11g Secure Files Overview Inderpal S. Johal. Inderpal S. Johal, Data Softech Inc.

Events Committee Format WP Olympic Format Options for 2016 Mid-Year Report April 2012

Chapter 4 (sort of): How Universal Are Turing Machines? CS105: Great Insights in Computer Science

IWR PLANNING SUITE II PCOP WEBINAR SERIES. Laura Witherow (IWR) and Monique Savage (MVP) 26 July

G53CLP Constraint Logic Programming

Dive Planet. Manual. Rev Basic User Interface. 2 How to organize your dives. 3 Statistics. 4 Location Service and Map View.

We release Mascot Server 2.6 at the end of last year. There have been a number of changes and improvements in the search engine and reports.

Fantasy Baseball Filename: baseball

2005 FISA Extraordinary Congress

CSE 3401: Intro to AI & LP Uninformed Search II

Racing Rules of Sailing

[CROSS COUNTRY SCORING]

- 2 - Companion Web Site. Back Cover. Synopsis

Markings Technical Committee Chapter 3H: Roundabout Markings APPROVED IN NCUTCD COUNCIL ON JANUARY 20, 2006

Topic No January 2000 Manual on Uniform Traffic Studies Revised July Chapter 8 GAP STUDY

Search I. Tuomas Sandholm Carnegie Mellon University Computer Science Department. [Read Russell & Norvig Chapter 3]

CS 221 PROJECT FINAL

All Work and no Play. Is that work? Work, work, work. You might head off to your job one day, sit at a computer, and type away at the keys.

Chapter 3 BUS IMPROVEMENT CONCEPTS

CSE 3402: Intro to Artificial Intelligence Uninformed Search II

Spacecraft Simulation Tool. Debbie Clancy JHU/APL

Repetition Structures

5.1 Introduction. Learning Objectives

UNITY 2 TM. Air Server Series 2 Operators Manual. Version 1.0. February 2008

Twitter Analysis of IPL cricket match using GICA method

Evaluating the Influence of R3 Treatments on Fishing License Sales in Pennsylvania

Xactix XeF2 OPERATION MANUAL

Look again at the election of the student council president used in the previous activities.

FIG: 27.1 Tool String

[CROSS COUNTRY SCORING]

Background Information. Project Instructions. Problem Statement. EXAM REVIEW PROJECT Microsoft Excel Review Baseball Hall of Fame Problem

Full-Time People and Registrations Version 5.0

13. TIDES Tidal waters

CT PET-2018 Part - B Phd COMPUTER APPLICATION Sample Question Paper

Simulating Major League Baseball Games

Spreading Activation in Soar: An Update

Autodesk Moldflow Communicator Process settings

Relational Schema Design. Part II: Schema Decomposition. Example of Bad Design. Result of bad design: Anomalies

STATIONARY SPRINKLER IRRIGATION SYSTEM

RML Example 26: pto. First Try at a PTO. PTO with a table inside

MIKE NET AND RELNET: WHICH APPROACH TO RELIABILITY ANALYSIS IS BETTER?

N E W J U D G I N G S Y S T E M F O R A R T I S T I C R O L L E R S K A T I N G C O M P E T I T I O N S THE SYSTEM.

Participation of Women in the Joint Statistical Meetings: Beginning in 1996, the American Statistical Association s Committee on Women in

Hydrostatics Physics Lab XI

STIPumpCard. User Manual

Prerequisites: Layout:

Excel Solver Case: Beach Town Lifeguard Scheduling

Flyweight Pattern. Flyweight: Intent. Use sharing to support large numbers of fine-grained objects efficiently. CSIE Department, NTUT Chien-Hung Liu

Cloud real-time single-elimination tournament chart system

A Nomogram Of Performances In Endurance Running Based On Logarithmic Model Of Péronnet-Thibault

4.1 Why is the Equilibrium Diameter Important?

Acknowledgments...iii. Section 1: Introduction to /ILE... 1

Real World Search Problems. CS 331: Artificial Intelligence Uninformed Search. Simpler Search Problems. Example: Oregon. Search Problem Formulation

501 (OPTIONS: L01, L02, L03, L04, L05, L06) This game is played the same as 301 except a player starts with 501 points.

MP-70/50 Series Scoreboard Controller User Guide

The system design must obey these constraints. The system is to have the minimum cost (capital plus operating) while meeting the constraints.

At each type of conflict location, the risk is affected by certain parameters:

A IMPROVED VOGEL S APPROXIMATIO METHOD FOR THE TRA SPORTATIO PROBLEM. Serdar Korukoğlu 1 and Serkan Ballı 2.

Application of Bayesian Networks to Shopping Assistance

Package mrchmadness. April 9, 2017

For IEC use only. Technical Committee TC3: Information structures, documentation and graphical symbols

living with the lab control of salinity 2012 David Hall

Report. User guide for the NOWIcob tool (D5.1-75) Author(s) Matthias Hofmann Iver Bakken Sperstad Magne Kolstad

3 Revising Diagnostic Imaging PARs

Trawl fishery management of Eastern Arabian Sea

PLA 2.1. Release Notes PLA 2.1 (build 604) December 21, 2015

Solving MINLPs with BARON. Mustafa Kılınç & Nick Sahinidis Department of Chemical Engineering Carnegie Mellon University

An Efficient Code Compression Technique using Application-Aware Bitmask and Dictionary Selection Methods

Performance/Pilot Math

Transcription:

Database Management Systems Chapter 5 SQL: Queries, Constraints, Triggers 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 R1 sid bid day 22 101 10/10/96 58 103 11/12/96 sid sname rating age 22 dustin 7 45.0 31 lubber 8 55.5 58 rusty 10 35.0 sid sname rating age 28 yuppy 9 35.0 31 lubber 8 55.5 44 guppy 5 35.0 58 rusty 10 35.0 1

Basic SQL Query select-list: columns to be retained. from-list: a cross-product of tables. qualification: selection conditions DISTINCT is an optional keyword indicating that the answer should not contain duplicates. Default is that duplicates are not eliminated! SELECT FROM WHERE [DISTINCT] select-list from-list qualification Conceptual Evaluation Strategy Semantics of an SQL query defined in terms of the following conceptual evaluation strategy: Compute the cross-product of from-list. Discard resulting tuples if they fail qualifications. Delete attributes that are not in select-list. If DISTINCT is specified, eliminate duplicate rows. This strategy is probably the least efficient way to compute a query! An optimizer will find more efficient strategies to compute the same answers. 2

Example of Conceptual Evaluation, Reserves R WHERE S.sid=R.sid AND R.bid=103 (sid) sname rating age (sid) bid day 22 dustin 7 45.0 22 101 10/10/96 22 dustin 7 45.0 58 103 11/12/96 31 lubber 8 55.5 22 101 10/10/96 31 lubber 8 55.5 58 103 11/12/96 58 rusty 10 35.0 22 101 10/10/96 58 rusty 10 35.0 58 103 11/12/96 A Note on Range Variables OR Really needed only if the same relation appears twice in the FROM clause. The previous query can also be written as: FROM Sailors AS S, Reserves AS R WHERE S.sid=R.sid AND bid=103; SELECT sname FROM Sailors, Reserves WHERE Sailors.sid=Reserves.sid AND bid=103; Optional It is good style, however, to use range variables always! 3

Q1: Find the sids of sailors who ve reserved a red boat SELECT R.sid FROM Boats B, Reserves R WHERE B.bid=R.bid AND B.color= red ; A join of two tables followed by a selection on the color of boats. (( Boats) Re ) sid color ' red' serves Q2: Find the names of sailors who ve reserved a red boat, Reserves R, Boats B WHERE S.sid=R.sid AND R.bid = B.bid AND B.color = red ; A join of three tables, followed by a selection on the color of boats. sname (( Boats) Re serves Sailors) color ' red ' 4

Q4: Find names of sailors who ve reserved at least one boat, Reserves R WHERE S.sid=R.sid; sname(reserves Sailors) Expressions and Strings in select-list Select-list: expression AS column_name expression: any arithmetic or string expression over column names and constants. column_name: a new name for this column in the output of the query. Qualification: expression1 = expression2. 5

Q17: Compute increments for the ratings of persons who have sailed two different boats on the same day. Q17_1: who have sailed two different boats on the same day? Please show their sailor ids. SELECT DISTINCT R1.sid 1, Reserves R2 WHERE R1.sid=R2.sid AND R1.day = R2.day AND R1.bid<>R2.bid; Q17_2: Names of persons who have sailed two different boats on the same day. SELECT distinct S.sname, Reserves R1, Reserves R2 WHERE S.sid=R1.sid AND R1.sid=R2.sid AND R1.day = R2.day AND R1.bid<>R2.bid; Q17: Compute increments for the ratings of persons who have sailed two different boats on the same day. SELECT distinct S.sname, S.rating+1 AS rating, Reserves R1, Reserves R2 WHERE S.sid=R1.sid AND S.sid=R2.sid AND R1.day = R2.day AND R1.bid<>R2.bid; 6

Q18: Find names of sailors whose ratings are different in the given way. SELECT S1.sname AS name1, S2.sname AS name2 1, Sailors S2 WHERE 2*S1.rating = S2.rating; Expressions and Strings in select-list 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. Q: 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. SELECT S.age, age1=s.age-5, 2*S.age AS age2 WHERE S.sname LIKE B_%B 7

Union UNION/OR: Can be used to compute the union of any two union-compatible sets of tuples. Q: Find sids of sailors who ve reserved a red or a green boat SELECT R.sid FROM Boats B, Reserves R WHERE R.bid=B.bid AND (B.color= red OR B.color= green ); SELECT R1.sid FROM Boats B1, Reserves R1 WHERE R1.bid=B1.bid AND B1.color= red UNION SELECT R2.sid FROM Boats B2, Reserves R2 WHERE R2.bid=B2.bid AND B2.color= green Union Q: Find all sids of sailors who ve a rating of 10 or reserved boat 104. SELECT S.sid WHERE S.rating =10 UNION SELECT R.sid WHERE R.bid = 104 8

Intersect INTERSECT/AND: Can be used to compute the intersection of any two intersect-compatible sets of tuples. Q: Find sid s of sailors who ve reserved a red and a green boat SELECT R1.sid 1, Reserves R2, Boats B1, Boats B2 WHERE R1.sid = R2.sid and R1.bid=B1.bid AND R2.bid=B2.bid AND (B1.color= red AND B2.color= green ) SELECT R1.sid FROM Boats B1, Reserves R1 WHERE R1.bid=B1.bid AND B1.color= red INTERSECT SELECT R2.sid FROM Boats B2, Reserves R2 WHERE R2.bid=B2.bid AND B2.color= green Not supported in mysql Except (Difference) EXCEPT: Can be used to compute the set-difference of any two except-compatible sets of tuples. Q: Find sid s of sailors who ve reserved red boats but not green boats. SELECT R1.sid FROM Boats B1, Reserves R1 WHERE R1.bid=B1.bid AND B1.color= red EXCEPT SELECT R2.sid FROM Boats B2, Reserves R2 WHERE R2.bid=B2.bid AND B2.color= green Not supported in mysql 9

Nested Query One of the most powerful features of SQL. A query that has another query embedded within it. Q: Find names of sailors who ve reserved boat #103: WHERE S.sid IN (SELECT R.sid WHERE R.bid=103) SELECT distinct S.sname, Reserves R WHERE S.sid=R.sid AND bid=103 Non-nested Query Nested Query Example Q: Find names of sailors who ve not reserved boat #103: WHERE S.sid NOT IN (SELECT R.sid WHERE R.bid=103) Works as Difference Q: Find names of sailors who ve not reserved boat #103, but other boats., Reserves R WHERE S.sid=R.sid AND bid<>103 Non-nested Query 10

Nested Query Example Q: Find names of sailors who ve reserved a red boat: WHERE S.sid IN (SELECT R.sid WHERE R.bid IN ( SELECT B.bid FROM Boats B WHERE B.color = red )) Non-nested Query, Reserves R, Boats B WHERE S.sid=R.sid AND R.bid = B.bid AND B.color = red ; Q: Find names of sailors who ve not reserved a red boat: WHERE S.sid NOT IN (SELECT R.sid WHERE R.bid IN ( SELECT B.bid FROM Boats B WHERE B.color = red )) Nested Query Example Works as WHERE S.sid NOT IN (SELECT R.sid Difference, Boats B WHERE R.bid = B.bid and B.color = red )) 11

Q: Find names of sailors who ve reserved a boat that is not red: WHERE S.sid IN (SELECT R.sid WHERE R.bid NOT IN ( SELECT B.bid FROM Boats B WHERE B.color = red )), Reserves R, Boats B WHERE S.sid=R.sid AND R.bid = B.bid and B.color <> red; Q: Find names of sailors who ve reserved both a red and a green boat., 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 Sailor S2, Boats B2, Reserves R2 WHERE S2.sid = R2.sid AND R2.bid=B2.bid AND B2.color= green ) SELECT R1.sid FROM Boats B1, Reserves R1 WHERE R1.bid=B1.bid AND B1.color= red INTERSECT SELECT R2.sid FROM Boats B2, Reserves R2 WHERE R2.bid=B2.bid AND B2.color= green 12

Correlated Nested Queries The inner query could depend on the row currently being examined in the outer query. Illustrates why, in general, subquery must be recomputed for each Sailors tuple. EXISTS is another set comparison operator, like IN. Q: Find names of sailors who ve reserved boat #103: WHERE EXISTS (SELECT * WHERE R.bid=103 AND S.sid=R.sid) Set-comparison Operators Also available: op ANY, op ALL, op IN,,,,, Q: Find sailors whose rating is greater than some sailor called Horatio: SELECT * WHERE S.rating > ANY (SELECT S2.rating 2 WHERE S2.sname= Horatio ) If there were no sailor called this name, the comparison is false, an empty set will be returned. 13

Q: Find sailors whose rating is greater than every sailor called Horatio: SELECT * WHERE S.rating > ALL (SELECT S2.rating 2 WHERE S2.sname= Horatio ) If there were no sailor called this name, the comparison is true, all sailors will be returned. Q: Find sailors with highest rating. SELECT S.sid WHERE S.rating > =ALL (SELECT S2.rating 2) Division is SQL Q: Find sailors who ve reserved all boats. WHERE NOT EXISTS ((SELECT B.bid FROM Boats B) EXCEPT (SELECT R.bid WHERE R.sid=S.sid)) 14