SQL Subqueries Objectives of the Lecture : To consider the general nature of subqueries. To consider simple versus correlated subqueries. To consider the.

Slides:



Advertisements
Similar presentations
© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Joins and Sub-queries in SQL.
Advertisements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5 Modified by Donghui Zhang.
Group functions cannot be used in the WHERE clause: SELECT type_code FROM d_songs WHERE SUM (duration) = 100; (this will give an error)
Set operators (UNION, UNION ALL, MINUS, INTERSECT) [SQL]
INTRODUCTION TO DATABASE MANAGEMENT SYSTEMS Dr. Adam Anthony Fall 2012.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Multiple-Column Subqueries 12. Objectives After completing this lesson, you should be able to do the following: Write a multiple-column subquery Describe.
Copyright  Oracle Corporation, All rights reserved. 6 Writing Correlated Subqueries.
Instructor: Craig Duckett CASE, ORDER BY, GROUP BY, HAVING, Subqueries
1 DDL – subquery Sen Zhang. 2 Objectives What is a subquery? Learn how to create nested SQL queries Read sample scripts and book for different kinds of.
Structured Query Language Chapter Three (Excerpts) DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Database Systems More SQL Database Design -- More SQL1.
Structured Query Language Chapter Three DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
A Guide to SQL, Seventh Edition. Objectives Retrieve data from a database using SQL commands Use compound conditions Use computed columns Use the SQL.
Retrievals & Projections Objectives of the Lecture : To consider retrieval actions from a DB; To consider using relational algebra for defining relations;
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
Chapter 3 Single-Table Queries
Banner and the SQL Select Statement: Part Four (Multiple Connected Select Statements) Mark Holliday Department of Mathematics and Computer Science Western.
CSc-340 2b1 Introduction to SQL Chapter 3 [2 of 2] Null Values Aggregate Functions Nested Subqueries Modification of the Database.
4-1 Copyright  Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
1 ICS 184: Introduction to Data Management Lecture Note 10 SQL as a Query Language (Cont.)
CSC271 Database Systems Lecture # 12. Summary: Previous Lecture  Row selection using WHERE clause  WHERE clause and search conditions  Sorting results.
Database Programming Sections 6 –Subqueries, Single Row Subqueries, Multiple-column subqueries, Multiple-row Subqueries, Correlated Subqueries 11/2/10,
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
DATABASE TRANSACTION. Transaction It is a logical unit of work that must succeed or fail in its entirety. A transaction is an atomic operation which may.
Nested Queries (Sub Queries) A nested query is a form of a SELECT command that appears inside another SQL statement. It is also termed as subquery. The.
Joins & Sub-queries. Oracle recognizes that you may want data that resides in multiple tables drawn together in some meaningful way. One of the most important.
Nitin Singh/AAO RTI ALLAHABAD 1 SQL Nitin Singh/AAO RTI ALLAHABAD 2 OBJECTIVES §What is SQL? §Types of SQL commands and their function §Query §Index.
NULLs & Outer Joins Objectives of the Lecture : To consider the use of NULLs in SQL. To consider Outer Join Operations, and their implementation in SQL.
1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.
IS 230Lecture 6Slide 1 Lecture 7 Advanced SQL Introduction to Database Systems IS 230 This is the instructor’s notes and student has to read the textbook.
SQL SeQueL -Structured Query Language SQL SQL better support for Algebraic operations SQL Post-Relational row and column types,
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
Topics Related to Attribute Values Objectives of the Lecture : To consider sorting relations by attribute values. To consider Triggers and their use for.
SQL advanced select using Oracle 1. 2 Select Simple –data from a single table Advanced –data from more tables join sub-queries.
Chapter 12 Subqueries and Merge Statements
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Subqueries These slides are licensed under.
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
Insert & Delete Objectives of the Lecture : To consider the insertion of tuples into a relation; To consider the deletion of tuples from a relation; To.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Relational State Assertions These slides.
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
Agenda for Class - 03/04/2014 Answer questions about HW#5 and HW#6 Review query syntax. Discuss group functions and summary output with the GROUP BY statement.
Database Programming Sections 6 –Subqueries, Single Row Subqueries, Multiple-row Subqueries, Correlated Subqueries.
1 Chapter 3 Single Table Queries. 2 Simple Queries Query - a question represented in a way that the DBMS can understand Basic format SELECT-FROM Optional.
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
Chapter 11 – Data Manipulation: Relational Algebra and SQL1 Unit 9: Data Manipulation: Relational Algebra and SQL IT238: Data Modeling and Database Design.
Using Subqueries to Solve Queries
Multiple-Column Subqueries
MySQL Subquery Source: Dev.MySql.com
Chapter 12 Subqueries and MERGE Oracle 10g: SQL
Aggregating Data Using Group Functions
Instructor: Craig Duckett Lecture 09: Tuesday, April 25th, 2017
Subqueries.
Subqueries Schedule: Timing Topic 25 minutes Lecture
Using Subqueries to Solve Queries
Aggregating Data Using Group Functions
Writing Correlated Subqueries
(SQL) Aggregating Data Using Group Functions
Aggregating Data Using Group Functions
Aggregating Data Using Group Functions
Structured Query Language
Using Subqueries to Solve Queries
SQL Subquery.
Subqueries Schedule: Timing Topic 25 minutes Lecture
Using Subqueries to Solve Queries
Using Subqueries to Solve Queries
Subqueries Schedule: Timing Topic 25 minutes Lecture
Subqueries Schedule: Timing Topic 25 minutes Lecture
Presentation transcript:

SQL Subqueries Objectives of the Lecture : To consider the general nature of subqueries. To consider simple versus correlated subqueries. To consider the usage of subqueries.

Closure Under the Algebra / SQL l Every relational algebra operator takes either one or two relations as operands, and returns a relation as a result. l Similarly in SQL, every SELECT statement - i.e. a query - takes one or more tables as an operand(s) and returns another table as a result. l Thus it is possible to use a SELECT statement as a subquery within another SQL statement wherever that outer statement needs a value, i.e. within : l CREATE TABLE statements, l INSERT statements, l DELETE statements, l UPDATE statements, l SELECT statements.

Subquery SELECT STATEMENTS l Anything allowable in a normal SELECT statement is allowed in a subquery SELECT statement, except : l the keyword DISTINCT in the SELECT phrase, l an ORDER BY phrase. This is because SQL can always ignore duplicate rows and row ordering in the ‘sub table’ result. l For queries, subqueries are logically unnecessary in SQL. However this was not originally realised. They are retained because they can be useful for some queries, by expressing them in a natural way. l Depending on the circumstances, the subquery may be required to return a single value,a column of values, a row of values,a table of values.

Subquery with CREATE TABLE Example :- CREATE TABLE Manager AS SELECT Emp_No, Emp_Name, Salary FROM Emp JOIN Dept ON( Emp_No = Manager_No ) ; Column names are inherited. Columns which are NOT NULL in ‘Emp’ are also NOT NULL in ‘Manager’. No other Integrity Constraints are inherited. The subquery returns a TABLE OF VALUES to ‘Manager’.

Subquery with INSERT Example :- INSERT INTO Manager SELECT Emp_No, Emp_Name, Salary FROM Emp JOIN Dept ON( Emp_No = Manager_No ) ; The usual rules about data types apply. The subquery returns a TABLE OF VALUES to ‘Manager’.

Subquery with DELETE Example :- DELETE FROM Emp WHERE Dept_No = ( SELECT Dept_No FROM Dept WHERE Dept_Name = ‘Sales’ ) ; The subquery returns a SINGLE VALUE to ‘Emp’. If the subquery returns more than one value, then an ERROR will occur. All the employees of the ‘Sales’ department will be deleted.

Subquery with UPDATE Example :- UPDATE Emp SET ( Salary, Dept_No ) = ( SELECT Salary, Dept_No FROM Emp WHERE Emp_No = ‘E5’ ) WHEREEmp_No = ‘E8’ The subquery returns a SINGLE ROW VALUE to ‘Emp’. If the subquery returns more than one value, then an ERROR will occur. The order of columns in the outer and inner statements must be consistent. Employee ‘E8’ is assigned the salary and department of employee ‘E5’.

Subquery within a Query Wherever an expression can appear in a SELECT statement, it can be replaced by a subquery/SELECT statement. DBMSs that meet the SQL3 standard. SELECT..... FROM..... WHERE..... Subquery Originally subqueries could only be used in the WHERE phrase. Most subqueries are still used in the WHERE phrase. This allows the SQL built-in order of execution to be overcome  more like relational algebra.

Which child(ren) are taller than Chloe ? Example : Subquery within a Query (1) SELECT statement to query “How tall is Chloe ?” SELECT statement to query “Who is taller than... ?” Work ‘bottom upwards’; work out which data is to be passed to the next query up.

Which child(ren) are taller than Chloe ? Example : Subquery within a Query (2) SELECT Height FROM Pupil WHERE Name = 'Chloe‘ ; Height SELECT Name, Height FROM Pupil WHERE Height > 1.12 ; Name Height Ali 1.18 Bill 1.17 How tall is Chloe ? Who is taller than 1.12 ?

Which child(ren) are taller than Chloe ? Example : Subquery within a Query (3) SELECT Name, Height FROM Pupil WHERE Height > ( SELECT Height FROM Pupil WHERE Name = 'Chloe‘ ) ; Name Height Ali 1.18 Bill 1.17 Columns compared must be of the same data type.

Which child(ren) are taller and older than Chloe ? Multiple Subqueries : Example SELECT NameFROM Pupil WHERE Height > ( SELECT Height FROM Pupil WHERE Name = 'Chloe‘ ) AND DoB < ( SELECT DoB FROM Pupil WHERE Name = 'Chloe‘ ) ; Name Ali Bill

Get the names of those employees who work in the department with the biggest budget. Nested Subqueries : Example SELECT Emp_Name FROM Emp WHERE Dept_No = ( SELECT Dept_No FROM Dept WHERE Budget = ( SELECT Max( Budget ) FROM Dept ) ) ; Still work ‘bottom upwards’. Subqueries can be nested to any depth.

Single Value Comparisons SELECT FROM WHERE θ ( SELECT FROM WHERE ) ; θ can be = <> > >= < <= Must ensure that the subquery returns a SINGLE VALUE, i.e. a table of one row and one column, or an ERROR results.

Ensuring Single Value Comparisons SELECT Emp_Name FROM Emp WHERE Dept_No = ( SELECT Dept_No FROM Dept WHERE Budget = ( SELECT Max( Budget ) FROM Dept ) ) ; Use an aggregate function, AND treat the table as one group. In the WHERE comparison, use a column and comparison that is GUARANTEED to return one row in SELECT. Example : a Candidate Key with an ‘=‘ comparison. Suppose these is more than one department with the maximum-sized budget ?!

Multiple Value Comparisons SELECT FROM WHERE θθ ( SELECT FROM WHERE ) ; θθ can be IN NOT IN θ ANY θ ALL EXISTS NOT EXISTS The subquery can return MULTIPLE VALUES, i.e. one column of many rows. However there is no problem if only one row is returned. θ is any of =, <>, >, >=, <, <=

Get the names of those employees who work in departments with budgets worth over £125,000. IN Comparison : Example SELECT Emp_Name FROM Emp WHERE Dept_No IN ( SELECT Dept_No FROM Dept WHERE Budget > ) ; IN is the same comparator as is used with a set of literal values. Example : WHERE Dept_No IN ( ‘D1’, ‘D2’, ‘D3’ ). The subquery is used to supply the values instead of them being written out. Can’t use ‘=‘ comparison. Subquery can return many department numbers.

ANY and ALL : Examples They are used to compare a single value with each of the individual values in the set returned by the subquery. SELECT Emp_Name FROM Emp WHERE Salary >ANY ( SELECT Salary FROM Emp WHERE Dept_No = ‘D1’ ) ; SELECT Emp_Name FROM Emp WHERE Salary >ALL ( SELECT Salary FROM Emp WHERE Dept_No = ‘D1’ ) ; If ‘>’ is true for at least one value, ANY returns true, else false. If ‘>’ is true for every value, ALL returns true, else false.

EXISTS : Example SELECT Emp_Name, Salary, Emp_No FROM Emp WHERE EXISTS ( SELECT * FROM Emp WHERE Salary > ) ; Example : all the employees’ names, IDs, and salaries are retrieved if there is at least one employee with a salary in excess of £100,000, presumably a suspicious circumstance ! If the subquery contains at least one row, then EXISTS returns true, otherwise false. Hence there is normally no interest in the particular column(s) returned, and so * is used in the SELECT phrase.

‘Simple’ and ‘Correlated’ Subqueries l All the subqueries seen so far are evaluated once, and the value returned used to evaluate the outer query. These are called Simple or Non-Correlated queries. l A Correlated subquery is one that contains a reference to one or more tables in its outer query, and therefore needs to be evaluated once for each row returned in its outer query. Example : SELECT *FROM Emp WHERE EXISTS ( SELECT * FROM Dept WHERE Manager_No = Emp_No ) ; Get the employee details of all department managers.

‘Correlated’ Subquery : Example (2) SELECT Dept_Name FROM Dept WHERE ‘M’ IN ( SELECT Marital_Status FROM Emp WHERE Emp.Dept_No = Dept.Dept_No ) ; Get the names of the departments that have married employees. Because of the WHERE phrase, the subquery must be executed for every row in Dept in order to see whether that row is to be retrieved or not. Note : ‘M’ does not appear in table Dept.

Correlated Subquery : Example (3) Cannot use a Natural Join here, because only those rows of Alloc are required that correspond to the same project as the row of Proj currently being evaluated Which projects have exactly 2 employees working on them ? The Natural Join is executed once. If the join result has exactly 2 rows, all the rows of Proj are retrieved; otherwise no rows are retrieved SELECT * FROM Proj WHERE 2 = ( SELECT Count(*)FROM Alloc WHERE Alloc.Proj_No = Proj.Proj_No ) ; One table. SELECT * FROM Proj WHERE 2 = ( SELECT Count(*) FROM Alloc NATURAL JOIN Proj ) ; Two tables. Note required form of comparison.

Subquery in a FROM Phrase SELECT Max( AvSal ) AS MaxAvSal FROM ( SELECT Avg( Salary ) AS AvSal, Dept_No FROM Emp GROUP BY Dept_No ) AS Emp_Averages; Example : Get the maximum of the average departmental salaries. This is a useful way of applying an aggregate function to the result of an aggregate function. This use of a subquery is sometimes known as an Inline View.

Subquery in a SELECT Phrase SELECT Emp_Name, ( Salary - ( SELECT Min( Salary ) FROM Emp ) ) AS Additional FROM Emp ; Example : Get the additional amount of salary that each employee receives over and above the minimum company salary. This is a useful way of doing a scalar calculation in each row that requires the resulting value of an aggregation.