Chapter 6. SQL: SubQueries

Similar documents
Objective. The goal is to review material covered in Chapters 1-5. Do the following questions from the book.

Lecture 03. Spring 2018 Borough of Manhattan Community College

CS317 File and Database Systems

Lecture 03. Fall 2017 Borough of Manhattan Community College

STRUCTURED QUERY LANGUAGE (SQL)

CMP-3440 Database Systems


Chapter 6. SQL Data Manipulation

Chapter 5. Relational Algebra and Relational Calculus

Database Technologies. Madalina CROITORU IUT Montpellier

CS317 File and Database Systems

CMP-3440 Database Systems

Relational Algebra and Relational Calculus. Pearson Education Limited 1995,

Two hours UNIVERSITY OF MANCHESTER SCHOOL OF COMPUTER SCIENCE

3ISY402 DATABASE SYSTEMS

SQL DDL. Intro SQL CREATE TABLE ALTER TABLE Data types Service-based database in Visual Studio Database in PHPMyAdmin

Database Systems. A Practical Approach to Design, Implementation, and Management. Database Systems. Thomas Connolly Carolyn Begg

ADVANCED QUERY AND VIEWS

CS317 File and Database Systems

1 P a g e D a t a b a s e o l d p a p e r b y w a s i m

Institute of Southern Punjab, Multan

Theory 2 Hours/Week 2 credits

6.9 List the names and addresses of all guests in London, alphabetically ordered by name.

Relational Data Model ( 관계형데이터모델 )

Example 1 - Create Horizontal View. Example 2 - Create Vertical View. Views. Views

Lecture 05. Spring 2018 Borough of Manhattan Community College

SQL grouping, views & modifying data

Lecture 6 Structured Query Language (SQL)

Lecture 5 Data Definition Language (DDL)

PART III SOLUTIONS TO REVIEW QUESTIONS AND EXERCISES

DB Creation with SQL DDL

Querying Data with Transact SQL

Standard Query Language. SQL: Data Definition Transparencies

Lecture 07. Spring 2018 Borough of Manhattan Community College

Subquery: There are basically three types of subqueries are:

Physical Database Design

RELATIONAL DATA MODEL

2.2.2.Relational Database concept

Query Processing Transparencies. Pearson Education Limited 1995, 2005

COMP102: Introduction to Databases, 5 & 6

The Relational Algebra

Transforming ER to Relational Schema

Querying Data with Transact-SQL

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

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

Database Technologies. Madalina CROITORU IUT Montpellier

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

Intermediate SQL ( )

Nested Queries. Dr Paolo Guagliardo. Aggregate results in WHERE The right way. Fall 2018

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

OVERVIEW OF RELATIONAL DATABASES: KEYS

Conceptual Database Design

Cheltenham Courseware Microsoft Access 2003 Manual - Advanced Level SAMPLE

Database Technologies. Madalina CROITORU IUT Montpellier

After completing this course, participants will be able to:

Computer Science. Syllabus for B.Sc. (As per UGC CBCS w.e.f ) Department of Mathematics Osmania University Hyderabad Telangana

Computer Science. Syllabus for B.Sc. Department of Computer Science. (As per UGC CBCS w.e.f ) Palamuru University Mahabubnagar Telangana

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 8 Advanced SQL

Relational Model. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

CS 582 Database Management Systems II

Querying Data with Transact-SQL (20761)

Entity Relationship Modeling

Fundamentals of Database Systems

Oracle Database: Introduction to SQL Ed 2

Syllabus for Computer Science B.Sc. Programme under Choice Based Credit System

SQL queries II. Set operations and joins

SQL Aggregation and Grouping. Outline

SQL Aggregation and Grouping. Davood Rafiei

EXISTS NOT EXISTS WITH

20461: Querying Microsoft SQL Server 2014 Databases

Objectives. After completing this lesson, you should be able to do the following:

QUERYING MICROSOFT SQL SERVER COURSE OUTLINE. Course: 20461C; Duration: 5 Days; Instructor-led

Relational Database Management Systems for Epidemiologists: SQL Part II

SQL Data Querying and Views

Database Concepts and Applications

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

20461D: Querying Microsoft SQL Server

Normalisation. Normalisation. Normalisation

Step 1: Create and Check ER Model

INF1383 -Bancos de Dados

20761C: Querying Data with Transact-SQL

T-SQL Training: T-SQL for SQL Server for Developers

CS317 File and Database Systems

Database Management Systems,

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

Querying Microsoft SQL Server

COURSE OUTLINE: Querying Microsoft SQL Server

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

"Charting the Course... MOC C: Querying Data with Transact-SQL. Course Summary

Database Systems. A Practical Approach to Design, Implementation, and Management. Database Systems. Thomas Connolly Carolyn Begg

SQL Data Query Language

COURSE OUTLINE MOC 20461: QUERYING MICROSOFT SQL SERVER 2014

Querying Microsoft SQL Server

Chapter 9: Object-Based Databases

Microsoft Querying Microsoft SQL Server 2014

Querying Data with Transact-SQL

Querying Data with Transact-SQL

SQL: Data Querying. B0B36DBS, BD6B36DBS: Database Systems. h p:// Lecture 4

Writing Analytical Queries for Business Intelligence

Microsoft Querying Data with Transact-SQL - Performance Course

Transcription:

Chapter 6 SQL: SubQueries Pearson Education 2009

Definition A subquery contains one or more nested Select statements Example: List the staff who work in the branch at 163 Main St SELECT staffno, fname, lname, position FROM Staff WHERE branchno = (SELECT branchno FROM Branch WHERE street = 163 Main St ); 2

Subquery Resolution If the branchno corresponding to 163 Main St is B003, then the query resolves to: SELECT staffno, fname, lname, position FROM Staff WHERE branchno = B003 ; 3

Equivalent Query with Join Sometimes, but not always, a subquery can be replaced with a join: SELECT staffno, fname, lname, position FROM Staff, Branch WHERE (Staff.branchNo =Branch.branchNo) AND (street = 163 Main St ); 4

Types of Subqueries Scalar subquery: Returns a single value Example: See previous example Example: List all staff whose salary is greater than the average salary, and show by how much their salary is greater than the average SELECT staffno, fname, lname, position, salary - (SELECT AVG(salary) FROM Staff) AS saldiff FROM Staff WHERE salary > (SELECT AVG(salary) FROM Staff); 5

Subquery Resolution Suppose the average salary is 17,000. Then the query resolves as: SELECT staffno, fname, lname, position, salary 17000 FROM Staff WHERE salary > 17000; 6

Using SQL Variables You can use SQL variables to store intermediate results ² 1) Limited to storing single values (i.e., scalar values) ² 2) Cannot store tables ² 3) Prefix name with @ Example SELECT @avgsalary := AVG(salary) FROM Staff; SELECT staffno, fname, lname, position, salary - @avgsalary AS saldiff FROM Staff ² WHERE salary > @avgsalary; To suppress any output when you make the assignment: SELECT AVG(salary) INTO @avgsalary FROM Staff; 7

Types of Subqueries (Cont) Row subquery: Returns multiple columns possibly multiple rows Only used in an EXISTS predicate Example: Find all staff who work in a London branch office SELECT staffno, fname, lname, position FROM Staff s WHERE EXISTS (SELECT * FROM Branch b WHERE s.branchno = b.branchno AND b.city = London ); 8

Types of Subqueries (cont) Table subquery: Returns a table suitable for use with IN (only 1 column allowed in result returned by subquery) Example: List the properties that are handled by staff who work in the branch at 163 Main St SELECT propertyno, street, city, postcode, type, rooms, rent FROM PropertyForRent WHERE staffno IN (SELECT staffno FROM Staff WHERE branchno = (SELECT branchno FROM Branch WHERE street = 163 Main St ); 9

SELECT propertyno, street, city, postcode, type, rooms, rent FROM PropertyForRent WHERE staffno IN (SELECT staffno FROM Staff WHERE branchno = (SELECT branchno FROM Branch WHERE street = 163 Main St ); SELECT * FROM PropertyForRent p NATURAL JOIN staff s ² NATURAL Join Branch b ² WHERE b.street = 163 Main St ; 10

Subquery Rules ORDER BY clause may not be used in a subquery The subquery SELECT list must consist of a single column name or expression (except row queries in EXIST predicates) By default, column names in a subquery refer to the table name in the FROM clause of the subquery. ² It is possible to refer to a table in a FROM clause of an outer query by qualifying the column name When a subquery is one of the two operands involved in a comparison, the subquery must be the right hand side operand ² Example: In the previous aggregate subquery, it would not be permissible to have written:» WHERE (SELECT AVG(salary) FROM Staff) < salary; 11

Exercise List all guests currently staying at the Grosvenor Hotel ² Hotel (hotelno, hotelname, city) ² Room (roomno, hotelno, type, price) ² Booking (hotelno, guestno, datefrom, dateto, roomno) ² Guest (guestno, guestname, guestaddress) 12

Exercise List all guests currently staying at the Grosvenor Hotel ² Hotel (hotelno, hotelname, city) ² Room (roomno, hotelno, type, price) ² Booking (hotelno, guestno, datefrom, dateto, roomno) ² Guest (guestno, guestname, guestaddress) SELECT * FROM Guest WHERE guestno IN (SELECT guestno FROM Booking WHERE (CURRENT_DATE BETWEEN datefrom AND DATE_SUB(dateTo, INTERVAL 1 DAY) ) AND hotelno = (SELECT hotelno FROM Hotel WHERE hotelname = Grosvenor Hotel )); 13

A Join Solution to the Exercise There is also a solution that involves join, without using a subquery SELECT Guest.guestNo, Guest.guestName, Guest.guestAddr FROM Guest, Booking, Hotel WHERE (Guest.guestNo = Booking.guestNo) AND (CURRENT_DATE BETWEEN datefrom AND DATE_SUB(dateTo, INTERVAL 1 DAY) ) AND (Booking.hotelNo = Hotel.hotelNo) AND (hotelname = 'Grosvenor Hotel'); 14