Chapter 6 The database Language SQL as a tutorial

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

SQL Continued! Outerjoins, Aggregations, Grouping, Data Modification

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

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

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

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

Database Design and Programming

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 SUBQUERIES DATABASE SYSTEMS AND CONCEPTS, CSCI 3030U, UOIT, COURSE INSTRUCTOR: JAREK SZLICHTA

Chapter 6 The database Language SQL as a tutorial

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

SQL: Data Manipulation Language

Databases 1. Defining Tables, Constraints

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

Chapter 2 The relational Model of data. Relational model introduction

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

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

Databases-1 Lecture-01. Introduction, Relational Algebra

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

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

Constraints. Local and Global Constraints Triggers

SQL. The Basics Advanced Manipulation Constraints Authorization 1. 1

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

SQL DATA DEFINITION LANGUAGE

CSCI3030U Database Models

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

I Relational Database Modeling how to define

Relational Query Languages

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

SQL DATA DEFINITION LANGUAGE

SQL DATA DEFINITION LANGUAGE

SQL: Data Definition Language

I Relational Database Modeling how to define

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

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

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

Constraints and Triggers

The Relational Model

From E/R Diagrams to Relations

Entity-Relationship Model. Purpose of E/R Model

CS54100: Database Systems

Chapter 2 The relational Model of data. Relational algebra

Relational Algebra and SQL. Basic Operations Algebra of Bags

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

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

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 Algebra. Algebra of Bags

CS54100: Database Systems

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

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

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

CompSci 516: Database Systems

SQL: Part II. Announcements (September 18) Incomplete information. CPS 116 Introduction to Database Systems. Homework #1 due today (11:59pm)

Relational Algebra and SQL

Announcements (September 18) SQL: Part II. Solution 1. Incomplete information. Solution 3? Solution 2. Homework #1 due today (11:59pm)

Querying Data with Transact SQL

Querying Data with Transact-SQL

Introduction to Database Systems CSE 414

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

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

SQL queries II. Set operations and joins

Relational Model, Relational Algebra, and SQL

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

Chapter 3: Introduction to SQL

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

Relational Algebra. B term 2004: lecture 10, 11

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

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

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

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

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

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

Computing for Medicine (C4M) Seminar 3: Databases. Michelle Craig Associate Professor, Teaching Stream

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

SQL Aggregation and Grouping. Outline

SQL Aggregation and Grouping. Davood Rafiei

Relational model continued. Understanding how to use the relational model. Summary of board example: with Copies as weak entity

Entity-Relationship Model

CS411 Database Systems. 04: Relational Algebra Ch 2.4, 5.1

Relational Model & Algebra. Announcements (Tue. Sep. 3) Relational data model. CompSci 316 Introduction to Database Systems

On-Line Application Processing

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

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

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

Querying Data with Transact SQL Microsoft Official Curriculum (MOC 20761)

CMPT 354: Database System I. Lecture 3. SQL Basics

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

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

Chapter 3: Introduction to SQL

Course Modules for MCSA: SQL Server 2016 Database Development Training & Certification Course:

CIS 330: Applied Database Systems

Chapter 3: Introduction to SQL. Chapter 3: Introduction to SQL

They like one or more beers and frequent one. Bars have unique names and addresses. They. serve one or more beers and are frequented

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

Warehousing. Data Mining

The SQL data-definition language (DDL) allows defining :

Contains slides made by Naci Akkøk, Pål Halvorsen, Arthur M. Keller, Vera Goebel

Carnegie Mellon Univ. Dept. of Computer Science Database Applications. General Overview - rel. model. Overview - detailed - SQL

$99.95 per user. Writing Queries for SQL Server (2005/2008 Edition) CourseId: 160 Skill level: Run Time: 42+ hours (209 videos)

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

Transcription:

Chapter 6 The database Language SQL as a tutorial About SQL SQL is a standard database language, adopted by many commercial systems. ANSI SQL, SQL-92 or SQL2, SQL99 or SQL3 extends SQL2 with objectrelational features. SQL2003 is the collection of extensions to SQL3. How to query the database How to make modifications on database Transactions in SQL

Union, Intersection and Difference Union, intersection, and difference of relations are expressed by the following forms, each involving subqueries: ( subquery ) UNION ( subquery ) ( subquery ) INTERSECT ( subquery ) ( subquery ) EXCEPT ( subquery )

Example Likes(drinker, beer) Sells(bar, beer, price) Frequents(drinker, bar) find the drinkers and beers such that: 1. The drinker likes the beer, and 2. The drinker frequents at least one bar that sells the beer.

Solution (SELECT * FROM Likes) INTERSECT (SELECT drinker, beer FROM Sells, Frequents WHERE Frequents.bar = Sells.bar ); The drinker frequents a bar that sells the beer.

Set Semantics The default for union, intersection, and difference is set semantics. That is, duplicates are eliminated as the operation is applied.

Motivation: Efficiency When doing intersection or difference, it is most efficient to sort the relations first. At that point you may as well eliminate the duplicates anyway.

Bag Semantics Bag model: Select From-Where Motivation: When doing projection, it is easier to avoid eliminating duplicates. Just work tuple-at-a-time.

Controlling Duplicate Elimination Force the result to be a set by SELECT DISTINCT... Force the result to be a bag (i.e., don t eliminate duplicates) by ALL, as in... UNION ALL...

Example: DISTINCT Sells(bar, beer, price) find all the different prices charged for beers: SELECT DISTINCT price FROM Sells; Notice that without DISTINCT, each price would be listed as many times as there were bar/beer pairs at that price.

Example: ALL Force bag semantics with ALL Frequents(drinker, bar) Likes(drinker, beer) (SELECT drinker FROM Frequents) EXCEPT ALL (SELECT drinker FROM Likes); Lists drinkers who frequent more bars than they like beers, and does so as many times as the difference of those counts.

Classroom Exercise Assume R and S have the same schema Q1: (select * from R) INTERSECT ALL (select * from S) Q2: (select * from R) NATURAL JOIN (select * from S) a) Q1 and Q2 produce the same answer. b) The answer to Q1 is contained in the answer to Q2 c) The answer to Q2 is contained in the answer to Q1 d) Q1 and Q2 produce different answers.

Answer (b) As sets, both produce the intersection of R and S. However, SQL is a bag language. Suppose a tuple t appears m times in R and n times in S. Then T appears min(m,n) times in the answer to Q1. However, for the join, we pair all tuples of R with all tuples of S that agree in the common attributes (i.e., all attributes in this case), and we produce of copy for each successful pairing. Thus, Q2 produces mn copies of t. It is easy to verify that as long as m and n are nonnegative integers, min(m,n) <= mn.

Join Expressions SQL provides a number of expression forms that act like varieties of join in relational algebra. But using bag semantics, not set semantics. These expressions can be standalone queries or used in place of relations in a FROM clause.

Products and Natural Joins Natural join is obtained by: R NATURAL JOIN S; Product is obtained by: R CROSS JOIN S; Example: Likes NATURAL JOIN Serves; Relations can be parenthesized subexpressions, as well.

Theta Join R JOIN S ON <condition> is a theta-join, using <condition> for selection. Example: Drinkers(name, addr), Frequents(drinker, bar): Drinkers JOIN Frequents ON name = drinker; Results: all (n, a, d, b) quadruples such that drinker d lives at address a and frequents bar b.

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. LEFT = pad dangling tuples of R only. RIGHT = pad dangling tuples of S only. FULL = pad both; this choice is the default.

Classroom Demo: Set operations select sid from sc; select sid from sc union select sid from sc; select sid from sc union all select sid from sc; who has not chosen any courses? select sid from students except select sid from sc;

Demo: Theta-Join expressions select * from students, sc where students.sid=sc.sid; select * from students join sc on students.sid=sc.sid; select *from Students natural join sc; select * from students natural join sc where grade is not null;

Demo: Self join expressions pairs of students with the same average grade: select s1.sid, s2.sid from (select sid,avg(grade) as x from sc group by sid ) s1, (select sid, avg(grade) as x from sc group by sid) s2 where s1.x=s2.x and s1.sid < s2.sid;

Database Modifications A modification command does not return a result as a query does, but it changes the database in some way. There are 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.

Insertion 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 );

Specifying Attributes in INSERT Add to the relation name a list of attributes. Reasons : 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.

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 );

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

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.

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.

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

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

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

Example: Delete Many Tuples Beers(name, manf) Delete 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.

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?

Semantics of Deletion -- 2 The answer is that 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 in the original relation. 2. Delete the marked tuples.

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

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

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

Adding Attributes Change a relation schema by adding a new attribute ( column ) by: ALTER TABLE <name> ADD <attribute declaration>; Example: ALTER TABLE Bars ADD phone CHAR(16)DEFAULT unlisted ;

Deleting Attributes Remove an attribute from a relation schema by: ALTER TABLE <name> DROP <attribute>; Example: we don t really need the license attribute for bars: ALTER TABLE Bars DROP license;

Classroom Exercise let these students who have not chosen any courses to choose database course. (insert) update the corresponding information (update) delete those students who has taken more than 5 courses (delete)

Insert: these students who have not chosen any courses to choose database course select * from students where sid not in (select sid from sc); insert into sc(sid) select sid from students where sid not in (select sid from sc); update sc set cid=1, cname='database' where cid is null;

delete those students who has taken more than 5 courses delete from sc where sid in (select sid from sc group by sid having count(*) > 5); select sid,count(*) from sc group by sid;