SQL Continued! Outerjoins, Aggregations, Grouping, Data Modification

Similar documents
More SQL. Extended Relational Algebra Outerjoins, Grouping/Aggregation Insert/Delete/Update

Introduction to SQL. Multirelation Queries Subqueries. Slides are reused by the approval of Jeffrey Ullman s

EXTENDED RELATIONAL ALGEBRA OUTERJOINS, GROUPING/AGGREGATION INSERT/DELETE/UPDATE

Chapter 6 The database Language SQL as a tutorial

Database Design and Programming

Subqueries. Must use a tuple-variable to name tuples of the result

Why SQL? SQL is a very-high-level language. Database management system figures out best way to execute query

Introduction to SQL. Select-From-Where Statements Multirelation Queries Subqueries

Introduction to SQL. Select-From-Where Statements Multirelation Queries Subqueries. Slides are reused by the approval of Jeffrey Ullman s

Introduction to SQL SELECT-FROM-WHERE STATEMENTS SUBQUERIES DATABASE SYSTEMS AND CONCEPTS, CSCI 3030U, UOIT, COURSE INSTRUCTOR: JAREK SZLICHTA

SQL: Data Manipulation Language

Chapter 6 The database Language SQL as a tutorial

CS 464/564 Introduction to Database Management System Instructor: Abdullah Mueen

CSC 343 Winter SQL: Aggregation, Joins, and Triggers MICHAEL LIUT

CS 317/387. A Relation is a Table. Schemas. Towards SQL - Relational Algebra. name manf Winterbrew Pete s Bud Lite Anheuser-Busch Beers

Databases 1. Defining Tables, Constraints

Chapter 2 The relational Model of data. Relational model introduction

A tuple is dangling if it doesn't join with any

Grouping Operator. Applying γ L (R) Recall: Outerjoin. Example: Grouping/Aggregation. γ A,B,AVG(C)->X (R) =??

Beersèname, manfè. Likesèdrinker, beerè. Sellsèbar, beer, priceè. Frequentsèdrinker, barè

CS145 Introduction. About CS145 Relational Model, Schemas, SQL Semistructured Model, XML

Structured Query Language Continued. Rose-Hulman Institute of Technology Curt Clifton

SQL. The Basics Advanced Manipulation Constraints Authorization 1. 1

CSCI3030U Database Models

Transactions, Views, Indexes. Controlling Concurrent Behavior Virtual and Materialized Views Speeding Accesses to Data

Constraints. Local and Global Constraints Triggers

Databases-1 Lecture-01. Introduction, Relational Algebra

Views, Indexes, Authorization. Views. Views 8/6/18. Virtual and Materialized Views Speeding Accesses to Data Grant/Revoke Priviledges

CS54100: Database Systems

I Relational Database Modeling how to define

SQL DATA DEFINITION LANGUAGE

I Relational Database Modeling how to define

Entity-Relationship Model. Purpose of E/R Model

The Extended Algebra. Duplicate Elimination. Sorting. Example: Duplicate Elimination

SQL: Data Definition Language

SQL DATA DEFINITION LANGUAGE

SQL DATA DEFINITION LANGUAGE

Constraints and Triggers

From E/R Diagrams to Relations

Likesèdrinker, beerè. Sellsèbar, beer, priceè. Frequentsèdrinker, barè

Relational Algebra and SQL

Most database operations involve On- Line Transaction Processing (OTLP).

Interpretation is not exactly ëmissing value." There could be many reasons why no value is

On-Line Application Processing

The Relational Model

Relational Model, Relational Algebra, and SQL

Warehousing. Data Mining

Object-Oriented Database Languages. Object Description Language Object Query Language

Introduction to Database Systems CSE 414

e e Conceptual design begins with the collection of requirements and results needed from the database (ER Diag.)

Introduction to Transactions: Controlling Concurrent "Behavior" Virtual and Materialized Views" Indexes: Speeding Accesses to Data"

Missing Information. We ve assumed every tuple has a value for every attribute. But sometimes information is missing. Two common scenarios:

CSC 261/461 Database Systems Lecture 5. Fall 2017

Outerjoins, Constraints, Triggers

Recap and Schedule. Till Now: Today: Ø Query Languages: Relational Algebra; SQL. Ø Datalog A logical query language. Ø SQL Recursion.

CS54100: Database Systems

Entity-Relationship Model

Relational Algebra and SQL. Basic Operations Algebra of Bags

types, but key declarations and constraints Similar CREATE X commands for other schema ëdrop X name" deletes the created element of beer VARCHARè20è,

Design Techniques. 1. Avoid redundancy 2. Limit the use of weak entity sets 3. Don t use an entity set when an attribute will do

Chapter 2 The relational Model of data. Relational algebra

CSCD43: Database Systems Technology. Lecture 4

Relational Algebra. Algebra of Bags

Lecture 03: SQL. Friday, April 2 nd, Dan Suciu Spring

Relational Algebra BASIC OPERATIONS DATABASE SYSTEMS AND CONCEPTS, CSCI 3030U, UOIT, COURSE INSTRUCTOR: JAREK SZLICHTA

CIS 330: Applied Database Systems

Introduction to Database Systems CSE 414

Logical Operators and aggregation

Chapter 7: Constraints and Triggers. Foreign Keys Local and Global Constraints Triggers

Database Management Systems. Chapter 5

Basic form of SQL Queries

Polls on Piazza. Open for 2 days Outline today: Next time: "witnesses" (traditionally students find this topic the most difficult)

Introduction to Database Systems CSE 444

Announcements (September 14) SQL: Part I SQL. Creating and dropping tables. Basic queries: SFW statement. Example: reading a table

CS 464/564 Introduction to Database Management System Instructor: Abdullah Mueen

SQL: Queries, Programming, Triggers

ER Model. CSC 343 Winter 2018 MICHAEL LIUT

SQL queries II. Set operations and joins

SQL. Chapter 5 FROM WHERE

Logical Query Languages. Motivation: 1. Logical rules extend more naturally to. recursive queries than does relational algebra. Used in SQL recursion.

The Relational Data Model. Functional Dependencies. Example. Functional Dependencies

SQL: Queries, Constraints, Triggers

SQL: Data Manipulation Language. csc343, Introduction to Databases Diane Horton Winter 2017

Querying Data with Transact SQL

Design Theory for Relational Databases

SELECT Product.name, Purchase.store FROM Product JOIN Purchase ON Product.name = Purchase.prodName

Relational Model. Lecture #6 Autumn, Fall, 2001, LRX

Querying Data with Transact-SQL

From Relational Algebra to the Structured Query Language. Rose-Hulman Institute of Technology Curt Clifton

Introduction to Data Management CSE 344

Schedule. Today: Feb. 21 (TH) Feb. 28 (TH) Feb. 26 (T) Mar. 5 (T) Read Sections , Project Part 6 due.

COMP 330: SQL 3. Chris Jermaine and Kia Teymourian Rice University

Principles of Database Systems CSE 544. Lecture #2 SQL, Relational Algebra, Relational Calculus

SQL: csc343, Introduction to Databases Renée J. Miller and Fatemeh Nargesian and Sina Sina Meraji. Winter 2018

Chapter 10 Advanced topics in relational databases

Midterm Review. Winter Lecture 13

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

Lecture 3 SQL. Shuigeng Zhou. September 23, 2008 School of Computer Science Fudan University

Database Systems CSE 303. Outline. Lecture 06: SQL. What is Sub-query? Sub-query in WHERE clause Subquery

SQL (Structured Query Language)

Transcription:

SQL Continued! Outerjoins, Aggregations, Grouping, Data Modification 1

Outerjoins R OUTER JOIN S is the core of an outerjoin expression. It is modified by: 1. Optional NATURAL in front of OUTER. 2. Optional ON <condition> after JOIN. 3. Optional LEFT, RIGHT, or FULL before OUTER. Only one LEFT = pad dangling tuples of R only. of these RIGHT = pad dangling tuples of S only. FULL = pad both; this choice is the default. 2

Outer Join Example a b 1 2 3 NULL R c d 2 5 NULL 6 S a b c d 1 2 2 5 R OUTER JOIN S on b=c; 3 NULL NULL NULL NULL NULL NULL 6 3

All-in-one example (1) R (A, B) S (B, C, D) A B B C D 1 2 2 4 6 3 4 4 6 8 5 6 5 7 9 R CROSS JOIN S A R.B S.B C D 1 2 2 4 6 1 2 4 6 8 1 2 5 7 9 3 4 2 4 6 3 4 4 6 8 3 4 5 7 9 5 6 2 4 6 5 6 4 6 8 5 6 5 7 9 4

All-in-one example (2) R NATURAL JOIN S A B C D 1 2 4 6 3 4 6 8 R JOIN S ON R.B=S.D A R.B S.B C D 5 6 2 4 6 R OUTER JOIN S ON R.B=S.B A R.B S.B C D 1 2 2 4 6 3 4 4 6 8 5 6 NULL NULL NULL NULL NULL 5 7 9 R NATURAL OUTER JOIN S A B C D 1 2 4 6 3 4 6 8 5 6 NULL NULL NULL 5 7 9 R (A, B) S (B, C, D) A B B C D 1 2 3 4 5 6 2 4 6 4 6 8 5 7 9 5

All-in-one example (3) R RIGHT OUTER JOIN S ON R.B=S.B A R.B S.B C D 1 2 2 4 6 3 4 4 6 8 NULL NULL 5 7 9 R NATURAL LEFT OUTER JOIN S A B C D 1 2 4 6 3 4 6 8 5 6 NULL NULL R (A, B) S (B, C, D) A B B C D 1 2 3 4 5 6 2 4 6 4 6 8 5 7 9 6

Aggregations SUM, AVG, COUNT, MIN, and MAX can be applied to a column in a SELECT clause to produce that aggregation on the column. Also, COUNT(*) counts the number of tuples. 7

Example: Aggregation From Sells(bar, beer, price), find the average price of Bud: SELECT AVG(price) FROM Sells WHERE beer = Bud ; 8

Eliminating Duplicates in an Aggregation Use DISTINCT inside an aggregation. Example: find the number of different prices charged for Bud: SELECT COUNT(DISTINCT price) FROM Sells WHERE beer = Bud ; 9

NULL s Ignored in Aggregation NULL never contributes to a sum, average, or count, and can never be the minimum or maximum of a column. But if there are no non-null values in a column, then the result of the aggregation is NULL. Exception: COUNT of an empty set is 0. 10

Example: Effect of NULL s SELECT count(*) FROM Sells WHERE beer = Bud ; The number of bars that sell Bud. SELECT count(price) FROM Sells WHERE beer = Bud ; The number of bars that sell Bud at a known price. 11

Grouping We may follow a SELECT-FROM- WHERE expression by GROUP BY and a list of attributes. The relation that results from the SELECT-FROM-WHERE is grouped according to the values of all those attributes, and any aggregation is applied only within each group. 12

Example: Grouping From Sells(bar, beer, price), find the average price for each beer: SELECT beer, AVG(price) FROM Sells GROUP BY beer; beer AVG(price) Bud 2.33 13

Example: Grouping From Sells(bar, beer, price) and Frequents(drinker, bar), find for each drinker the average price of Bud at the bars they frequent: SELECT drinker, AVG(price) FROM Frequents, Sells WHERE beer = Bud AND Frequents.bar = Sells.bar GROUP BY drinker; Compute all drinker-barprice triples for Bud. Then group them by drinker. 14

Restriction on SELECT Lists With Aggregation If any aggregation is used, then each element of the SELECT list must be either: 1. Aggregated, or 2. An attribute on the GROUP BY list. 15

Illegal Query Example You might think you could find the bar that sells Bud the cheapest by: SELECT bar, MIN(price) FROM Sells WHERE beer = Bud ; But this query is illegal in SQL. 16

HAVING Clauses HAVING <condition> may follow a GROUP BY clause. If so, the condition applies to each group, and groups not satisfying the condition are eliminated. 17

Example: HAVING From Sells(bar, beer, price) and Beers(name, manf), find the average price of those beers that are either served in at least three bars or are manufactured by Pete s. 18

Solution SELECT beer, AVG(price) FROM Sells GROUP BY beer HAVING COUNT(bar) >= 3 OR beer IN (SELECT name FROM Beers WHERE manf = Pete s ); Beer groups with at least 3 non-null bars and also beer groups where the manufacturer is Pete s. Beers manufactured by Pete s. 19

Requirements on HAVING Conditions Anything goes in a subquery. Outside subqueries, they may refer to attributes only if they are either: 1. A grouping attribute, or 2. Aggregated (same condition as for SELECT clauses with aggregation). 20

Database Modifications A modification command does not return a result (as a query does), but changes the database in some way. Three kinds of modifications: 1. Insert a tuple or tuples. 2. Delete a tuple or tuples. 3. Update the value(s) of an existing tuple or tuples. 21

Insertion To insert a single tuple: INSERT INTO <relation> VALUES ( <list of values> ); Example: add to Likes(drinker, beer) the fact that Sally likes Bud. INSERT INTO Likes VALUES( Sally, Bud ); 22

Specifying Attributes in INSERT We may add to the relation name a list of attributes. Two reasons to do so: 1. We forget the standard order of attributes for the relation. 2. We don t have values for all attributes, and we want the system to fill in missing components with NULL or a default value. 23

Example: Specifying Attributes Another way to add the fact that Sally likes Bud to Likes(drinker, beer): INSERT INTO Likes(beer, drinker) VALUES( Bud, Sally ); 24

Adding Default Values In a CREATE TABLE statement, we can follow an attribute by DEFAULT and a value. When an inserted tuple has no value for that attribute, the default will be used. 25

Example: Default Values CREATE TABLE Drinkers ( name CHAR(30) PRIMARY KEY, ); addr CHAR(50) DEFAULT 123 Sesame St., phone CHAR(16) 26

Example: Default Values INSERT INTO Drinkers(name) VALUES( Sally ); Resulting tuple: name address phone Sally 123 Sesame St NULL 27

Inserting Many Tuples We may insert the entire result of a query into a relation, using the form: INSERT INTO <relation> ( <subquery> ); 28

Example: Insert a Subquery Using Frequents(drinker, bar), enter into the new relation PotBuddies(name) all of Sally s potential buddies, i.e., those drinkers who frequent at least one bar that Sally also frequents. 29

The other drinker Solution INSERT INTO PotBuddies (SELECT d2.drinker FROM Frequents d1, Frequents d2 WHERE d1.drinker = Sally AND ); d2.drinker <> Sally AND d1.bar = d2.bar Pairs of Drinker tuples where the first is for Sally, the second is for someone else, and the bars are the same. 30

Deletion To delete tuples satisfying a condition from some relation: DELETE FROM <relation> WHERE <condition>; 31

Example: Deletion Delete from Likes(drinker, beer) the fact that Sally likes Bud: DELETE FROM Likes WHERE drinker = Sally AND beer = Bud ; 32

Example: Delete all Tuples Make the relation Likes empty: DELETE FROM Likes; Note no WHERE clause needed. 33

Example: Delete Some Tuples Delete from Beers(name, manf) all beers for which there is another beer by the same manufacturer. DELETE FROM Beers b WHERE EXISTS ( SELECT name FROM Beers WHERE manf = b.manf AND name <> b.name); Beers with the same manufacturer and a different name from the name of the beer represented by tuple b. 34

Semantics of Deletion --- (1) Suppose Anheuser-Busch makes only Bud and Bud Lite. Suppose we come to the tuple b for Bud first. The subquery is nonempty, because of the Bud Lite tuple, so we delete Bud. Now, when b is the tuple for Bud Lite, do we delete that tuple too? 35

Semantics of Deletion --- (2) Answer: we do delete Bud Lite as well. The reason is that deletion proceeds in two stages: 1. Mark all tuples for which the WHERE condition is satisfied. 2. Delete the marked tuples. 36

Updates To change certain attributes in certain tuples of a relation: UPDATE <relation> SET <list of attribute assignments> WHERE <condition on tuples>; 37

Example: Update Change drinker Fred s phone number to 555-1212: UPDATE Drinkers SET phone = 555-1212 WHERE name = Fred ; 38

Example: Update Several Tuples Make $4 the maximum price for beer: UPDATE Sells SET price = 4.00 WHERE price > 4.00; 39

References in your textbook Chapter 6 6.4 6.5 40

Homework from your textbook 6.3.7 6.4.7 6.5.2 (6.5.2 of second edition, a, c, d solutions given in course homepage 41