Subqueries. So far when data has been filtered the filter has been known and simply added to the Where clause but often you don’t know what the filter.

Slides:



Advertisements
Similar presentations
© Abdou Illia MIS Spring 2014
Advertisements

A Guide to SQL, Seventh Edition. Objectives Use joins to retrieve data from more than one table Use the IN and EXISTS operators to query multiple tables.
1 Advanced SQL Queries. 2 Example Tables Used Reserves sidbidday /10/04 11/12/04 Sailors sidsnameratingage Dustin Lubber Rusty.
 Database is SQL1.mdb ◦ import using MySQL Migration Toolkit 
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 7: Subqueries and Set Operations.
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)MySQL Recap.
Clarity Educational Community Clarity Educational Community Creating and Tuning SQL Queries that Engage Users.
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.
Inclass Test Revision Database Technology Level I Lecture and Seminar Revision.
Mark Dixon Page 1 02 – Queries: Query by Example.
Structured Query Language Part I Chapter Three CIS 218.
1 Rewriting Intersect Queries Using In SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid = R.sid and R.bid = B.bid and B.color = ‘red’ INTERSECT.
Structured Query Language Chapter Three DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
1 Advanced SQL. 2 Consider the following relations: –pupil (pupil_name, address, class, birthyear) –subject (subject_name, class, teacher) –grades (pupil_name,
Some Introductory Programming 1. Structured Query Language - used for queries. - a standard database product. 2. Visual Basic for Applications - use of.
Create Forms Lesson 5. Software Orientation Creating Forms A form is a database object –enter, edit, or display data from a table or query Providing.
Relational databases.  Retrieving data from a database requires pulling data from multiple tables  Tables relate to each other in distinct ways, modelled.
Using Relational Databases and SQL Department of Computer Science California State University, Los Angeles Lecture 8: Subqueries.
Midterm Prep: OQL The mindset you should be in is object oriented. A number of you based on s/queries I have been answering are still in the relational.
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
Over the Past 2 weeks we have looked (in brief) at the basic elements of a relational database.  What we understand by the phrase database?  How the.
Programming using C# Joins SQL Injection Stored Procedures
Microsoft ® Access ® 2010 Training Create Queries for a New Database If a yellow security bar appears at the top of the screen in PowerPoint, click Enable.
Database Systems Microsoft Access Practical #3 Queries Nos 215.
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
Texas State Technical College DISCOVER! Inner Joins Let’s get together… yeah yeah yeah!
Day 13, Slide 1 U:/msu/course/cse/103 CSE 103 Students: Review INNER and OUTER JOINs, Subqueries. Others: Please save your.
Unit 4 Queries and Joins. Key Concepts Using the SELECT statement Statement clauses Subqueries Multiple table statements Using table pseudonyms Inner.
Relational Databases.  In week 1 we looked at the concept of a key, the primary key is a column/attribute that uniquely identifies the rest of the data.
G045 Lecture 08 DFD Level 1 Diagrams (Data Flow Diagrams Level 1)
1 IT420: Database Management and Organization SQL part 3 7 February 2006 Adina Crăiniceanu
CS 405G: Introduction to Database Systems Instructor: Jinze Liu Fall 2009.
NSF DUE ; Wen M. Andrews J. Sargeant Reynolds Community College Richmond, Virginia.
Subqueries.
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
1 SY306 Web and Databases for Cyber Operations Set #13: SQL SELECT Grouping and sub-queries.
# 1# 1 QueriesQueries How do we ask questions of the data? What is SELECT? What is FROM? What is WHERE? What is a calculated field? Spring 2010 CS105.
Relational Databases. SQL Sub-queries: queries within queries  So far when data has been filtered the filter has been known and simply added to the Where.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
44271: Database Design & Implementation Physical Data Modelling Ian Perry Room: C49 Tel Ext.: 7287
Drill Consider the following tables with the following fields: Student: FName, LName, StudentID, Age, Yr, Course Grades: ID, P1, P2, P3 1.Display the.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 5: SQL I Rob Gleasure robgleasure.com.
Database Programming Sections 6 –Subqueries, Single Row Subqueries, Multiple-row Subqueries, Correlated Subqueries.
COMPUTER PROGRAMMING Year 9 – lesson 1. Objective and Outcome Teaching Objective We are going to look at how to construct a computer program. We will.
1 Section 10 - Embedded SQL u Many computer languages allow you to embed SQL statements within the code (e.g. COBOL, PowerBuilder, C++, PL/SQL, etc.) u.
Select Complex Queries Database Management Fundamentals LESSON 3.1b.
Lecture 7: Subqueries Tarik Booker California State University, Los Angeles.
Introduction to SQL Server
MySQL Subquery Source: Dev.MySql.com
Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University
Multiple Table Queries
NURS6803 Clinical DB Design Katherine Sward, PhD, RN
LESSON Database Administration Fundamentals Inserting Data.
Dynamic Input with SQL Queries
Using the Set Operators
David M. Kroenke and David J
Using the Set Operators
CS 405G: Introduction to Database Systems
Database Queries.
JOINs JOINs can be used to combine tables A CROSS JOIN B
Introduction To Structured Query Language (SQL)
SQL Subquery.
M1G Introduction to Database Development
Introduction To Structured Query Language (SQL)
Using Subqueries to Solve Queries
Required queries FdSc inICT Module 107.
Using Subqueries to Solve Queries
Using the Set Operators
SELECT from Multiple Tables
Presentation transcript:

Subqueries

So far when data has been filtered the filter has been known and simply added to the Where clause but often you don’t know what the filter value is OR you don’t want to hardcode a value into the query. If the filter can be found elsewhere in the database then you can put a subquery in the WHERE clause. Allows for variable values (list student name who have got higher than average marks, name is in one table and average marks from another table.) Hard coding is poor practice Values change Etc. SQL Subqueries: queries within queries

Seminar task solution  Which tutors teach modules that all students have passed.  The question asked IF there were tutors who had all students pass, select all tutors who have passed students and select tutors who have failed then compare the results (2 queries needed)  Sub-queries are a better way  Put the query that lists the tutors with failures and add it to the where clause  Which tutors teach modules that all students have passed.  The question asked IF there were tutors who had all students pass, select all tutors who have passed students and select tutors who have failed then compare the results (2 queries needed)  Sub-queries are a better way  Put the query that lists the tutors with failures and add it to the where clause

Use sub-query Select name, sname From staffmember join class on (teacher = staffid) Join enrolled on (class.subjectid = subject.subjectid) Join marks on (subject.subjectid = marks.subjectid) Where mark >= 40 And staffid not in (Select staffid From staffmember join class on (teacher = staffid) Join marks using (subjectid) where mark < 40); Need to pull from Subject to get sname Who has passed Lists the names of staff With failed students and Excludes them

The basic concept is to pass a single value or many values from the subquery to the next query and so on When reading or writing SQL subqueries, you should start from the bottom upwards, working out which data is to be passed to the next query up.

Worked example.... Based on the database that is used for the ‘Tasks’ (University database) 1.Student names are held in the STUDENT table 2.Student marks are recorded in the MARKS table but marks are allocated against the STUDENTID If we want to list the names of the students who have failed the module we need to first identify the students who have failed the module, then use this list to select the names for students with those id’s

To identify the students who have failed module COMP1011 Select studentid From marks Where subjectid = ‘COMP1011’ And grade < 40; If we want to retrieve a name based on a student id Select stuname From student Where studentid = ; Simply swap the known value for the query that returns the ID Select stuname From Student Where studentid in ( select studentid From marks Where subjectid = ‘COMP1011’ And grade < 40); Why use IN?

Select stuname From Student Where studentid in ( select studentid From marks Where subjectid = ‘COMP1011’ And grade < 40); Retrieve a list of student id’s who have mark < 40 for COMP1011 Retrieve the name of the studentid’s in this list.

Rules for Subqueries: 1.The data types must match, if the studentid expects a number then the subquery must return a number. 2.Remember = means that it is expecting a single value, you must therefore be sure that the subquery returns only 1 result, if there is any doubt you should use the IN keyword. 3.You can nest / use as many subqueries as you like. 4.This is not a very efficient way of coding or pulling data from multiple tables, and you may be able to generate the required result using joins (covered later in the module)

Comparators =equal to >greater than >=greater than or equal to <less than <=less than or equal to <>not equal to and other keywords …… IN NOT IN ANY ALL

Exercise - do in pairs 1.Write a query that will list the names of who is older than the average student. TIPthe sub-query needs to select the average age of students this should be used then as a filter. select stuname from student where age > (select avg(age) from student); This will return 25 students of the 74 who are enrolled as being older than the average age.