Sub-Queries in SQL SQL. 3 Types of Sub-Queries. 3 Types of Sub-Queries. Scalar Sub-Query Example. Scalar Sub-Query Example

Similar documents
Database Systems SQL. A.R. Hurson 323 CS Building

Homework Assignment 2. Due Date: October 17th, CS425 - Database Organization Results

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

Relational Algebra and Calculus

Exam 1. March 12th, CS525 - Midterm Exam Solutions

Database Applications (15-415)

Functional Dependencies and Normalization. Instructor: Mohamed Eltabakh

Design Theory: Functional Dependencies and Normal Forms, Part I Instructor: Shel Finkelstein

Database Applications (15-415)

CS322: Database Systems Normalization

INTRODUCTION TO RELATIONAL DATABASE SYSTEMS

Relational Algebra & Calculus

P Q1 Q2 Q3 Q4 Q5 Tot (60) (20) (20) (20) (60) (20) (200) You are allotted a maximum of 4 hours to complete this exam.

Schema Refinement & Normalization Theory: Functional Dependencies INFS-614 INFS614, GMU 1

Constraints: Functional Dependencies

General Relativity by Robert M. Wald Chapter 2: Manifolds and Tensor Fields

Languages. Theory I: Database Foundations. Relational Algebra. Paradigms. Projection. Basic Operators. Jan-Georg Smaus (Georg Lausen)

SideNail. Martín Schonaker, Santiago Martínez

You are here! Query Processor. Recovery. Discussed here: DBMS. Task 3 is often called algebraic (or re-write) query optimization, while

Module 10: Query Optimization

Correlated subqueries. Query Optimization. Magic decorrelation. COUNT bug. Magic example (slide 2) Magic example (slide 1)

But RECAP. Why is losslessness important? An Instance of Relation NEWS. Suppose we decompose NEWS into: R1(S#, Sname) R2(City, Status)

Relational Algebra 2. Week 5

Constraints: Functional Dependencies

Normal Forms 1. ICS 321 Fall Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa

Query Processing. 3 steps: Parsing & Translation Optimization Evaluation

CS5300 Database Systems

Introduction to Data Management. Lecture #6 (Relational DB Design Theory)

INF1383 -Bancos de Dados

Introduction to Data Management. Lecture #12 (Relational Algebra II)

Design Theory for Relational Databases. Spring 2011 Instructor: Hassan Khosravi

Relational Algebra on Bags. Why Bags? Operations on Bags. Example: Bag Selection. σ A+B < 5 (R) = A B

General Overview - rel. model. Carnegie Mellon Univ. Dept. of Computer Science /615 DB Applications. Motivation. Overview - detailed

Database Systems Relational Algebra. A.R. Hurson 323 CS Building

Databases 2011 The Relational Algebra

b. hurricanescale.xml - Information on the Saffir-Simpson Hurricane Scale [3].

Intro to SQL. Two components. Data Definition Language (DDL): create table, etc. Data Manipulation Language (DML):

Chapter 10. Normalization Ext (from E&N and my editing)

b. states.xml Listing of states and their postal abbreviations.

Normal Forms (ii) ICS 321 Fall Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa

Query answering using views

GAV-sound with conjunctive queries

Schema Refinement & Normalization Theory

SCHEMA NORMALIZATION. CS 564- Fall 2015

Introduction to Data Management. Lecture #7 (Relational DB Design Theory II)

Relational operations

Schema Refinement and Normal Forms. Chapter 19

Database Design and Normalization

Databases Exam HT2016 Solution

Schema Refinement. Feb 4, 2010

CSC 261/461 Database Systems Lecture 10 (part 2) Spring 2018

Introduction to Database Systems CSE 414. Lecture 20: Design Theory

Basic Logic and Proof Techniques

CSE 132B Database Systems Applications

Chapter 11, Relational Database Design Algorithms and Further Dependencies

Schema Refinement and Normal Forms. Why schema refinement?

Schema Refinement: Other Dependencies and Higher Normal Forms

Relational algebra. Bence Molnár

Functional Dependency Theory II. Winter Lecture 21

Database Design and Implementation

Introduction to Data Management. Lecture #6 (Relational Design Theory)

Data Bases Data Mining Foundations of databases: from functional dependencies to normal forms

Section Summary. Section 1.5 9/9/2014

Semester: Spring

Matrices. Chapter Definitions and Notations

CIS Spring 2018 (instructor Val Tannen)

A Dichotomy. in in Probabilistic Databases. Joint work with Robert Fink. for Non-Repeating Queries with Negation Queries with Negation

Instructor: Amol Deshpande

Oracle Spatial: Essentials

HKBU: Tutorial 4

Lecture 24: Bloom Filters. Wednesday, June 2, 2010

Functional Dependencies & Normalization. Dr. Bassam Hammo

CS54100: Database Systems

L13: Normalization. CS3200 Database design (sp18 s2) 2/26/2018


Relationships between elements of sets occur in many contexts. Every day we deal with

Exercises 1 - Solutions

DATABASE DESIGN I - 1DL300

Quiz 2. Due November 26th, CS525 - Advanced Database Organization Solutions

Informationslogistik Unit 7: Conceptual Design of Databases Normalization

Geographic Information Systems (GIS) - Hardware and software in GIS

L14: Normalization. CS3200 Database design (sp18 s2) 3/1/2018

Chapter 16. Logic Programming. Topics. Logic Programming. Logic Programming Paradigm

Section Summary. Predicates Variables Quantifiers. Negating Quantifiers. Translating English to Logic Logic Programming (optional)

Profiling Sets for Preference Querying

Relational Database Design

CSE 303: Database. Outline. Lecture 10. First Normal Form (1NF) First Normal Form (1NF) 10/1/2016. Chapter 3: Design Theory of Relational Database

Schema Refinement and Normal Forms

Section 5.5: Matrices and Matrix Operations

Season Finale: Which one is better?

Database Normaliza/on. Debapriyo Majumdar DBMS Fall 2016 Indian Statistical Institute Kolkata

Lecture #7 (Relational Design Theory, cont d.)

Schema Refinement and Normal Forms Chapter 19

Department of Mathematics and Statistics Math B: Discrete Mathematics and Its Applications Test 1: October 19, 2006

Basic Math Review for CS1340

Declarative Programming Techniques

Schema Refinement and Normal Forms

Row Space, Column Space, and Nullspace

EECS-3421a: Test #2 Electrical Engineering & Computer Science York University

Schema Refinement. Yanlei Diao UMass Amherst. Slides Courtesy of R. Ramakrishnan and J. Gehrke

Transcription:

SQL Sub-Queries in SQL Peter Y. Wu Department of Computer and Information Systems Robert Morris University Data Definition Language Create table for schema and constraints Drop table Data Manipulation Language (Update) Insert, Delete, Update Data Manipulation Language (Query) Select-from-where: simple queries with conditions Select-from-where: aggregate functions and grouping Select-from-where: multiple tables with JOIN operation Select-from-where: sub-queries 2 3 Types of Sub-Queries An SQL query generates a result table even when there is no data! Scalar: table with one column and one row. Vector: table with one column only. Table: any number of columns and rows. An SQL sub-query is an SQL query embedded inside an (outer) SQL query. 3 Types of Sub-Queries We can use sub-queries in different ways: Scalar: as if it is a scalar involved in a term of the where conditions. Vector: as if it is a list/set involved in quantified comparison in where conditions. Table: used in the from clause as a table. An SQL sub-query can be embedded many many levels deep. 3 4 Scalar Sub-Query Example Find the s who died the latest. We will need a scalar result from the database. Scalar Sub-Query Example We need a scalar value from the database to be used in a query Piece PNo PName CNo 1000 The Four Seasons 1 1002 B-minor Mass 2 1003 Christmas Oratorio 2 1004 Missa Solemnis 3 1006 Classical Symphony 4 1007 Cinderella 4 select CName from where Died = (select max(died) from ); The sub-query generates a scalar result a number for our use in the (outer) query. 5 6 (c) Peter Y Wu - RMU. 1

Vector Sub-Query The SQL Query generates a result table with exactly one column. We use the result table as a list/set for comparison in the (outer) Query. The Vector sub-query may or may not contain duplicates. Let us review the use of list/set for comparison in the where conditions. 7 Vector Sub-Query Example Find the s who was born the earliest. without using an aggregate function... Piece PNo PName CNo 1000 The Four Seasons 1 1002 B-minor Mass 2 1003 Christmas Oratorio 2 1004 Missa Solemnis 3 1006 Classical Symphony 4 1007 Cinderella 4 8 Vector Sub-Query Example We need to find the minimum from a list of values (under column Born in the table). select CName from where Born <= all (select Born from ); The sub-query generates a list also called a vector for use in the (outer) query. The sub-query is called a vector sub-query. Vector Sub-query: returning a list select CName from where Born <= all (select Born from ); Picks the earliest born composer select CName from where not(born > any (select Born from )); The two conditions are logically equivalent; the two SQL statements give the same result for any set of data. Also called a nested QUERY, with inner query (that is, the sub-query returning a set) in the outer query. 9 10 SQL: quantified list comparison Note that these operator pairs are equivalent: = any ( ) and not <> all ( ) > any ( ) and not < all ( ) < any ( ) and not > all ( ) >= any ( ) and not <= all ( ) <= any ( ) and not >= all ( ) 11 Vector Sub-Query Examples STUDENT ENROLLMENT SSN First Last SSN CNum 123-45-6789 John Smith 123-45-6789 10011 111-22-3333 Ann Miller 111-22-3333 10066 543-76-9821 David Meyer 543-76-9821 10066 900-50-3000 Mary Jones 900-50-3000 10011 COURSE CNum Topic Title Instructor Enroll 10011 1050 Information Systems Wood 25 11007 2240 Data Structures Kovacs 30 10066 4240 Database Management Wu 28 21003 4770 Java Programming Wu 17 21004 4990 Electronic Commerce Kovacs 20 12 (c) Peter Y Wu - RMU. 2

Vector Sub-Query Examples STUDENT ENROLLMENT SSN First Last SSN CNum Section Term 123-45-6789 John Smith 123-45-6789 1050 A Spring 07 111-22-3333 Ann Miller 111-22-3333 4240 A Spring 08 543-76-9821 David Meyer 543-76-9821 4240 A Spring 08 900-50-3000 Mary Jones 900-50-3000 1050 A Spring 07 COURSE CNum Section Term Title Instructor Enroll 1050 A Spring 07 Information Systems Wood 25 2240 B Fall 08 Data Structures Kovacs 30 4240 A Spring 08 Database Systems Wu 28 4770 A Fall 07 Java Programming Wu 17 4990 A Spring 07 Electronic Commerce Kovacs 20 13 SQL Query with multiple tables List the names of the students who are taking courses taught by instructor Wu. select s.first, s.last from student s, enrollment e, course c and e.cnum = c.cnum and e.section = c.section and e.term = c.term and c.instructor = Wu ; 14 SQL operators: in, not in Select from where <term> [not] in (<list>); <term> in (<list>) is true if the value of term is found in the set. (4240, 4770); or using a vector sub-query: (select CNum from course where Instructor = Wu ); 15 Sub-query: returning a list (select CNum from course where Instructor= Wu ); The sub-query returns the set of CNum s of courses taught by Instructor Wu. The outer query therefore lists the students who take courses taught by Instructor Wu. 16 SQL: quantified list comparison operators in ( ) and not in ( ) Select from where <term> in (<list>); is the same as Select from where <term> = any (<list>); Select from where <term> not in (<list>); is the same as Select from where <term> <> all (<list>); 17 SQL operator: exists Select from where [not] exists (<list>); select s.first, s.last from student s where not exists (select * from enrollment e ); Listing all students who are not enrolled in any course at all. 18 (c) Peter Y Wu - RMU. 3

Sub-query: union of two lists union (select CNum from course where Title like Data% ); The sets returned are unioned: listing all students who take courses taught by Wu OR courses with a title beginning with Data. 19 Sub-query: union of two lists select s.first, s.last from student s, enrollment e union (4240, 4770); A set is a list of terms, or a vector sub-query. Recall that <list> ::= <term>,, <term> <sub-query> 20 Sub-query: union all select s.first, s.last from student s, enrollment e union all (4240, 4770); will not remove duplicates, simply concatenate the two result sets may be more efficient. Duplicate removal can be quite expensive. 21 Use a generated table in the from clause. Same as using a view a table defined by an SQL query: the data depends on the base tables the query selects from. A special form of insert statement also uses a table sub-query see example. 22 Select CNo, CName, 1+floor(Born/100) as Century from ; CNo CName Century 1 Vivaldi 17 2 Bach 17 3 Mozart 18 4 Prokofiev 19 5 Dvorak 19 23 CNo CName Century 1 Vivaldi 17 2 Bach 17 3 Mozart 18 4 Prokofiev 19 5 Dvorak 19 Select Century, count(cname) from (select CNo, CName, 1+floor(Born/100) as Century from ) group by Century; Century count(cname) 17 2 18 1 19 2 24 (c) Peter Y Wu - RMU. 4

SQL: insert two forms TWO forms of insert statement: insert into <table-name> [ (<column>,, <column>) ] values (<expr>,, <expr>); insert into <table-name> [ (<column>,, <column>) ] ( <select-statement> ); SQL insert: using a table sub-query create table T2 (N1 integer, N2 integer); insert into T2 (N2,N1) select c1,c2 from T1; C1 T1 C2 11 23 22 45 33 67 44 N1 T2 N2 23 11 45 22 67 33 44 25 26 (c) Peter Y Wu - RMU. 5