SQL:Union, Intersection, Difference. SQL: Natural Join

Similar documents
CS 232A: Database System Principles. Introduction. Introduction. Applications View of a Relational Database Management (RDBMS) System

Data Structure: Relational Model

CSE 135. Applications View of a Relational Database Management System (RDBMS) SQL. Persistent data structure. High-level API for access &modification

Views, assertions, and triggers

INF1383 -Bancos de Dados

Relational db: the origins. Relational Calculus (aka FO)

The Relational Algebra

CSCB20 Week 4. Introduction to Database and Web Application Programming. Anna Bretscher Winter 2017

Information Systems Engineering. SQL Structured Query Language DML Data Manipulation (sub)language

Querying Data with Transact SQL

Relational Algebra. Procedural language Six basic operators

Relational Model, Relational Algebra, and SQL

SQL. Lecture 4 SQL. Basic Structure. The select Clause. The select Clause (Cont.) The select Clause (Cont.) Basic Structure.

Chapter 5 Relational Algebra. Nguyen Thi Ai Thao

Chapter 8. Joined Relations. Joined Relations. SQL-99: Schema Definition, Basic Constraints, and Queries

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

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

NESTED QUERIES AND AGGREGATION CHAPTER 5 (6/E) CHAPTER 8 (5/E)

Chapter 4: SQL. Basic Structure

QQ Group

Lab # 6. Using Subqueries and Set Operators. Eng. Alaa O Shama

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

Relational Algebra and SQL

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

Multisets and Duplicates. SQL: Duplicate Semantics and NULL Values. How does this impact Queries?

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

Simple SQL Queries (2)

Querying Data with Transact-SQL

NESTED QUERIES AND AGGREGATION CHAPTER 5 (6/E) CHAPTER 8 (5/E)

CS 582 Database Management Systems II

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

Database Management Systems,

RELATIONAL ALGEBRA II. CS121: Relational Databases Fall 2017 Lecture 3

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

Chapter 3: Introduction to SQL

Chapter 3: SQL. Database System Concepts, 5th Ed. Silberschatz, Korth and Sudarshan See for conditions on re-use

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

Teradata SQL Features Overview Version

Slides by: Ms. Shree Jaswal

Chapter 3: SQL. Chapter 3: SQL

Chapter 6: Formal Relational Query Languages

Silberschatz, Korth and Sudarshan See for conditions on re-use

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

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

Relational Databases

SQL (Structured Query Language)

Querying Data with Transact-SQL

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

Chapter 3: Introduction to SQL

1) Introduction to SQL

Midterm Review. Winter Lecture 13

WHAT IS SQL. Database query language, which can also: Define structure of data Modify data Specify security constraints

Chapter 6 - Part II The Relational Algebra and Calculus

A subquery is a nested query inserted inside a large query Generally occurs with select, from, where Also known as inner query or inner select,

Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries Derived Relations Views Modification of the Database Data Definition

Database Systems SQL SL03

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

Database Management Systems Paper Solution

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

MTA Database Administrator Fundamentals Course

The SQL database language Parts of the SQL language

CSC 261/461 Database Systems Lecture 5. Fall 2017

Relational Algebra. Relational Algebra Overview. Relational Algebra Overview. Unary Relational Operations 8/19/2014. Relational Algebra Overview

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

An Introduction to Structured Query Language

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

Database Systems SQL SL03

Chapter 3: Relational Model

CS 377 Database Systems

DATABASE TECHNOLOGY - 1MB025

DATABASTEKNIK - 1DL116

Introduction to SQL Part 2 by Michael Hahsler Based on slides for CS145 Introduction to Databases (Stanford)

An Introduction to Structured Query Language

An Introduction to Structured Query Language

Textbook: Chapter 6! CS425 Fall 2013 Boris Glavic! Chapter 3: Formal Relational Query. Relational Algebra! Select Operation Example! Select Operation!

The Object Data Model

An Introduction to Structured Query Language

4. SQL - the Relational Database Language Standard 4.3 Data Manipulation Language (DML)

Incomplete Information: Null Values

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Chapter 6 Outline. Unary Relational Operations: SELECT and

An Introduction to Structured Query Language

Relational Algebra. Relational Algebra. 7/4/2017 Md. Golam Moazzam, Dept. of CSE, JU

Introduction to Query Processing and Query Optimization Techniques. Copyright 2011 Ramez Elmasri and Shamkant Navathe

Chapter 8 SQL-99: Schema Definition, Basic Constraints, and Queries

CMP-3440 Database Systems

Chapter 2: Relational Model

SQL and Incomp?ete Data

Chapter 6 The Relational Algebra and Calculus

Database System Concepts

ASSIGNMENT NO Computer System with Open Source Operating System. 2. Mysql

More SQL: Complex Queries, Triggers, Views, and Schema Modification

BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E)

Chapter 6 5/2/2008. Chapter Outline. Database State for COMPANY. The Relational Algebra and Calculus

DATABASE TECHNOLOGY - 1MB025

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

Querying Microsoft SQL Server 2014

Relational Algebra. ICOM 5016 Database Systems. Roadmap. R.A. Operators. Selection. Example: Selection. Relational Algebra. Fundamental Property

CSEN 501 CSEN501 - Databases I

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

In This Lecture. Yet More SQL SELECT ORDER BY. SQL SELECT Overview. ORDER BY Example. ORDER BY Example. Yet more SQL

Transcription:

SQL:Union, Intersection, Difference Union <SQL query 1> UNION <SQL query 2> Intersection <SQL query 1> INTERSECT <SQL query 2> Difference <SQL query 1> EXCEPT <SQL query 2> Find all actors or directors (SELECT Actor as Name FROM Movie) UNION (SELECT Director as Name FROM Movie) Find all actors who are not directors (SELECT Actor as Name FROM Movie) EXCEPT (SELECT Director as Name FROM Movie) 1 SQL: Natural Join Combines tuples from two tables by matching on common attributes movie director actor schedule theater Tango Berto Brando Hillcrest Tango Sky Berto Winger Paloma Tango Psycho Hitchcock Perkins Paloma Bambi Ken Psycho movie natural join schedule director actor theater Tango Berto Brando Hillcrest Tango Berto Brando Paloma Psycho Hitchcock Perkins Ken 2 1

SQL: Natural Join Find the directors of all movies showing in Hillcrest: select director from movie natural join schedule where theater = Hillcrest Many variations of joins are available in SQL (more on this later) 3 Null values in SQL testing if an attribute A is null: A is null, A is not null Ex: find all employees with unknown phone number select name from employee where phone is null arithmetic operations involving any null return null if Salary is null, then Salary + 1 evaluates to null comparisons involving any null return unknown new truth value if Salary is null, then Salary = 0 evaluates to unknown 4 2

Null values in SQL Boolean operations must now handle 3 truth values: true, false, unknown Boolean expressions involving unknown are evaluated using the following truth tables: AND true unknown unknown false unknown false unknown unknown unknown NOT unknown unknown OR true unknown true false unknown unknown unknown unknown unknown WHERE clause conditions evaluating to unknown are treated as false 5 Movie director actor Tango Berto Brando Psycho Hitch Perkins Bambi null null Examples Select Where dir = Hitch Psycho Select Where dir <> Hitch Tango Bambi 6 A: yes B: no 3

Movie director actor Tango Berto Brando Psycho Hitch Perkins Bambi null null Examples Select Where dir = Hitch Psycho Select Where dir <> Hitch Tango Bambi Tango 7 A: yes B: no B Movie director actor Tango Berto Brando Psycho Hitch Perkins Bambi null null Examples Select Where dir = null Bambi A: yes B: no 8 4

Movie director actor Tango Berto Brando Psycho Hitch Perkins Bambi null null Examples Select Where dir = null Bambi A: yes B: no Select Where dir is null Bambi 9 Null values in SQL Anomalies of null semantics if Salary is null, then: -- Salary* 0 evaluates to null -- Salary > 0 evaluates to unknown even if the domain is restricted to positive integers in the schema definition -- Consider the queries select name from employee where Salary <= 100 OR Salary > 100 and select name from employee Are these equivalent? A: yes B: no 10 5

Null values in SQL Anomalies of null semantics if Salary is null, then: -- Salary* 0 evaluates to null -- Salary > 0 evaluates to unknown even if the domain is restricted to positive integers in the schema definition -- Consider the queries select name from employee where Salary <= 100 OR Salary > 100 and select name from employee These are not equivalent if some salaries are null 11 Null Values and Aggregates Total all loan amounts select sum (amount ) from loan Above statement ignores null amounts Result is null if there is no non-null amount All aggregate operations except count(*) ignore tuples with null values on the aggregated attributes. Suppose R has a single attribute A. Are these equivalent? select count(*) from R select count(a) from R A: yes B: no 12 6

Null Values and Aggregates Total all loan amounts select sum (amount ) from loan Above statement ignores null amounts Result is null if there is no non-null amount All aggregate operations except count(*) ignore tuples with null values on the aggregated attributes. Suppose R has a single attribute A. Are these equivalent? select count(*) from R select count(a) from R A: yes B: no 13 Null Values and Group-By Null group-by attributes are treated like any other value R A B 2 3 2 5 Null 0 Null 1 Null 2 SELECT A, COUNT(B) AS C GROUP BY A A C 2 2 Null 3 14 7

SQL: creating nulls with Outer Joins Idea: to avoid losing tuples in natural joins, pad with null values P <outer join> Q natural left outer join: keep all tuples from left relation (P) natural right outer join: keep all tuples from right relation (Q) natural full outer join: keep all tuples from both relations 15 SQL: creating nulls with Outer Joins Combines tuples from two tables by matching on common attributes movie director actor schedule theater Tango Berto Brando Hillcrest Tango Sky Berto Winger Paloma Tango Psycho Hitchcock Hopkins Paloma Bambi Ken Psycho movie natural left outer join director actor theater schedule Tango Berto Brando Hillcrest Tango Berto Brando Paloma Psycho Hitchcock Hopkins Ken Sky Berto Winger null 16 8

SQL: creating nulls with Outer Joins Combines tuples from two tables by matching on common attributes movie director actor schedule theater Tango Berto Brando Hillcrest Tango Sky Berto Winger Paloma Tango Psycho Hitchcock Hopkins Paloma Bambi Ken Psycho movie natural right outer join director actor theater schedule Tango Berto Brando Hillcrest Tango Berto Brando Paloma Psycho Hitchcock Hopkins Ken Bambi null null Paloma 17 SQL: creating nulls with Outer Joins Combines tuples from two tables by matching on common attributes movie director actor schedule theater Tango Berto Brando Hillcrest Tango Sky Berto Winger Paloma Tango Psycho Hitchcock Hopkins Paloma Bambi Ken Psycho movie natural full outer join director actor theater schedule Tango Berto Brando Hillcrest Tango Berto Brando Paloma Psycho Hitchcock Hopkins Ken Bambi null null Paloma Sky Berto Winger null 18 9

Example: Find theaters showing only movies by Berto Select theater from schedule Where theater not in (select theater from schedule natural left outer join (select, director from movie where director = Berto ) where director is null) select, director from movie where director = Berto Movie director actor schedule theater Tango Berto Brando Hillcrest Tango Sky Berto Winger Paloma Tango Psycho Hitchcock Hopkins Paloma Psycho 19 Example: Find theaters showing only movies by Berto Select theater from schedule Where theater not in (select theater from schedule natural left outer join (select, director from movie where director = Berto ) where director is null) schedule natural left outer join (select, director from movie select, director from movie where where director director = Berto ) = Berto director schedule theater Tango Berto Hillcrest Tango Sky Berto Paloma Tango theater director Paloma Psycho Hillcrest Tango Berto Paloma Tango Berto Paloma Psycho null 20 10

Summary of basic SQL Queries A query in SQL can consist of up to six clauses, but only the first two, SELECT and FROM, are mandatory. The clauses are specified in the following order: SELECT <attribute list> FROM <table list> [WHERE <condition>] [GROUP BY <grouping attribute(s)>] [HAVING <group condition>] [ORDER BY <attribute list>] 21 Summary of basic SQL Queries (cont.) The SELECT-clause lists the attributes or functions to be retrieved The FROM-clause specifies all relations (or aliases) needed in the query but not those needed in nested queries The WHERE-clause specifies the conditions for selection of tuples from the relations specified in the FROM-clause GROUP BY specifies grouping attributes HAVING specifies a condition for selection of groups ORDER BY specifies an order for displaying the result of a query A query is evaluated by first applying the WHERE-clause, then GROUP BY and HAVING, and finally the SELECT-clause 22 11

SQL update language Insertions inserting tuples INSERT INTO R VALUES (v1,,vk); some values may be left NULL use results of queries for insertion INSERT INTO R SELECT FROM WHERE INSERT INTO Movie VALUES ( Matchpoint, Allen, Allen ); INSERT INTO Movie(Title,Director) VALUES ( Matchpoint, Allen ); INSERT INTO BertoMovie SELECT * FROM Movie WHERE Director = Berto 23 Deletion basic form: delete every tuple that satisfies <cond> DELETE FROM R WHERE <cond> Update basic form: update every tuple that satisfies <cond> in the way specified by the SET clause UPDATE R SET A1=<exp1>, Ak=<expk> WHERE <cond> SQL update language: Updates and Deletions Delete the movies that are not currently playing DELETE FROM Movie WHERE Title NOT IN SELECT Title FROM Schedule Change all Berto entries to Bertolucci UPDATE Movie SET Director= Bertolucci WHERE Director= Berto Increase all salaries in the Toys dept by 10% UPDATE Employee SET Salary = 1.1 * Salary WHERE Dept = Toys The rich get richer exercise: Increase 24 by 10% the salary of the employee with the highest salary 12

Example: delete all theaters showing more than one delete from schedule s where exists (select * from schedule where theater = s.theater and <> s.) Schedule theater Hillcrest Amour Hillcrest 0 dark 30 Paloma Django Result after delete? Schedule theater Paloma Django Assume this semantics: for each s in schedule if where clause is satisfied then delete s A: yes B: no 25 Example: delete all theaters showing more than one delete from schedule s where exists (select * from schedule where theater = s.theater and <> s.) Schedule theater Hillcrest Amour Hillcrest 0 dark 30 Paloma Django Result after delete? Schedule theater Paloma Django Correct Assume semantics: this semantics: 1. Find for each all theaters s in schedule showing more if where than clause one is satisfied 2. Delete then delete all theaters s found in 1. A: yes B: no 26 13