SQL Sub (or Nested ) Query. Examples Q: Find students whose GPA is below the average. –The criteria itself requires a SQL statement. –SELECT * FROM student.

Slides:



Advertisements
Similar presentations
Relational operators 1 Lecture 7 Relational Operators.
Advertisements

TURKISH STATISTICAL INSTITUTE 1 /34 SQL FUNDEMANTALS (Muscat, Oman)
DatabaseDatabase cs453 Lab8 1 Ins.Ebtesam AL-Etowi.
Set operators (UNION, UNION ALL, MINUS, INTERSECT) [SQL]
1 Lecture 3: Subqueries DCO11310 Database Systems and Design By Rose Chang.
Introduction to Oracle9i: SQL1 Subqueries. Introduction to Oracle9i: SQL2 Chapter Objectives Determine when it is appropriate to use a subquery Identify.
Querying Database ISYS 363. Basic Query Language Operations Selection Projection Join Aggregates: Max, Min, Sum, Avg, Count –Totals and SubTotals –GroupBy.
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.
SQLPlus Commands. Oracle Account Server: libra.sfsu.edu Telnet: libra.sfsu.edu How to use Oracle: –
Structured Query Language Review ISYS 650. Language Overview Three major components: –Data definition language, DDL Create, Drop and Alter Tables or Views.
Basic SQL Select Commands. Basic Relational Query Operations Selection Projection Natural Join Sorting Aggregation: Max, Min, Sum, Count, Avg –Total –Sub.
Querying Database ISYS 363. Basic Query Language Operations Selection Projection Join Aggregates: Max, Min, Sum, Avg, Count –Totals and SubTotals –GroupBy.
Relational Algebra. Set operations: Union, intersection, difference, Cartesian product Relational operations: Selection, projection, join, division.
Relational Operators, SQL, and Access Query ISYS 562.
Introduction to Oracle9i: SQL1 Views. Introduction to Oracle9i: SQL2 Chapter Objectives Create a view, using CREATE VIEW command or the CREATE OR REPLACE.
SQL: Interactive Queries (1) John Ortiz Lecture 11SQL: Interactive Queries (1)2 Basic Select Statement  Basic form of the select statement: select target-attribute-list.
Xin  Syntax ◦ SELECT field1 AS title1, field2 AS title2,... ◦ FROM table1, table2 ◦ WHERE conditions  Make a query that returns all records.
SQL advanced select using Oracle 1 7. Multiple Tables: Joins and Set Operations 8. Subqueries: Nested Queries.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
Fundamentals, Design, and Implementation, 9/e CPE 481 Database Processing Chapter 6 Structured Query Language (SQL) Instructor:Suthep Madarasmi, Ph.D.
CSC 405: Web Application And Engineering II7.1 Database Programming with SQL Aggregation and grouping with GROUP BY Aggregation and grouping with GROUP.
CSC271 Database Systems Lecture # 12. Summary: Previous Lecture  Row selection using WHERE clause  WHERE clause and search conditions  Sorting results.
Nested Queries (Sub-Queries). Objectives Learn how to run a query as a nested sub-query Condition on nested query Application of nested query Restriction.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Advanced SQL for Decision Support ISYS 650. Set Operators Union Intersect Difference Cartesian product.
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.
Oracle DML Dr. Bernard Chen Ph.D. University of Central Arkansas.
11 Copyright © Oracle Corporation, All rights reserved. Creating Views.
MIS 3053 Database Design & Applications The University of Tulsa Professor: Akhilesh Bajaj RM/SQL Lecture 5 © Akhilesh Bajaj, 2000, 2002, 2003, All.
1 Multiple Table Queries. 2 Objectives  Retrieve data from more than one table by joining tables  Using IN and EXISTS to query multiple tables  Nested.
Introduction to Access ISYS 363. Creating a New Database MS Office button/New –Blank database –New database name and location.
Copyright © Curt Hill Queries in SQL More options.
Relational Query Operators (Algebra). Relational Query Operators Set operations: Union, intersection, difference, Cartesian product Relational operations:
1 CSE 480: Database Systems Lecture 12: SQL (Nested queries and Aggregate functions)
Structured Query Language Introduction. Basic Select SELECT lname, fname, phone FROM employees; Employees Table LNAMEFNAMEPHONE JonesMark SmithSara
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
SQL advanced select using Oracle 1. 2 Select Simple –data from a single table Advanced –data from more tables join sub-queries.
1 IT420: Database Management and Organization SQL part 3 7 February 2006 Adina Crăiniceanu
Chapter 13 Views Oracle 10g: SQL. Oracle 10g: SQL2 Objectives Create a view, using CREATE VIEW command or the CREATE OR REPLACE VIEW command Employ the.
Querying Database ISYS 363.
Introduction to Access BUS 782. Creating a New Database MS Office button/New –Blank database –New database name and location.
Introduction to Access ISYS 363. Access Objects Tables –Open –Design –New –Wizard Queries Forms Reports Pages.
6 Copyright © 2007, Oracle. All rights reserved. Retrieving Data Using Subqueries.
Subqueries.
SQL Miscellaneous Topics. Views A database view is: – a virtual or logical table based on a query. – a stored query. CREATE VIEW viewname AS query; –CREATE.
The Student Registry Database Ian Van Houdt and Muna alfahad.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
Drill Consider the following tables with the following fields: Student: FName, LName, StudentID, Age, Yr, Course Grades: ID, P1, P2, P3 1.Display the.
Introduction to Access ISYS 363. Access Objects Tables –Open a table: Double click the table name –Home/View: Datasheet view Design view Queries Forms.
Set Operators. Union Intersect Difference Cartesian product.
ICOM 6005 – Database Management Systems Design Dr. Manuel Rodríguez-Martínez Electrical and Computer Engineering Department Lecture 10 – September 18,
Chapter 7 Subqueries. Chapter Objectives  Determine when it is appropriate to use a subquery  Identify which clauses can contain subqueries  Distinguish.
SQL: Interactive Queries (2) Prof. Weining Zhang Cs.utsa.edu.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
Advanced SQL. SQL - Nulls Nulls are not equal to anything - Null is not even equal to Null where columna != ‘ABC’ --this will not return records where.
Using Subqueries to Solve Queries
Subqueries Schedule: Timing Topic 25 minutes Lecture
Working with Tables: Join, Functions and Grouping
Using Subqueries to Solve Queries
Lecture#7: Fun with SQL (Part 2)
Querying Database ISYS 363.
File Processing with Excel’s List
Using Subqueries to Solve Queries
SQL Subquery.
Subqueries Schedule: Timing Topic 25 minutes Lecture
Using Subqueries to Solve Queries
Subqueries.
Using Subqueries to Solve Queries
Subqueries Schedule: Timing Topic 25 minutes Lecture
Subqueries Schedule: Timing Topic 25 minutes Lecture
Presentation transcript:

SQL Sub (or Nested ) Query

Examples Q: Find students whose GPA is below the average. –The criteria itself requires a SQL statement. –SELECT * FROM student WHERE gpa < (SELECT AVG(gpa) FROM student); Q: Find employees with higher than average salary. Q: Find employees who are hired before E2.

Sub Query with IN SELECT sid, sname FROM student WHERE sid in (‘S1’, ‘S2’); Use a subquery to retrieve keys that meet criteria. Example: Display students’ ID, name who owe university more than $2000. (Note: not showing balance) SELECT sid,sname FROM student WHERE SID IN (SELECT SID FROM account WHERE balance > 2000); Example: Display students’ ID, name and Balance who owe university more than $2000.

Sub Query with IN, NOT IN Use a subquery to retrieve keys that meet criteria. Q: Display faculty’s ID and name if the faculty advises at least one student. –SELECT fid, fname FROM faculty –WHERE fid IN (SELECT DISTINCT fid FROM student); Q: Display faculty’s name and name if the faculty does not advise any student. –SELECT fid, fname FROM faculty –WHERE fid NOT IN (SELECT DISTINCT fid FROM student);

Q: Display students’ ID and name who are taking at least one course. Q: Display students’ ID and name who do not take any course.

Sub Query with IN Q: Find students who take more than 5 courses and display their ID and name. –SELECT sid, sname FROM Student NATURAL JOIN Registration GROUP BY sid,sname HAVING COUNT(cid)>5; –SELECT sid, sname FROM student WHERE sid IN (SELECT sid FROM Registration GROUP BY sid HAVING COUNT(cid) > 5);

Sub Query with Join Display students’ ID, name and Balance who owe university more than $2000. SELECT sid,sname, Balance FROM student NATURAL JOIN (SELECT * FROM account WHERE balance > 2000); Display students’ ID and name who owe university more than $2000. SELECT sid,sname FROM student NATURAL JOIN (SELECT * FROM account WHERE balance > 2000); SELECT sid,sname FROM student WHERE SID IN (SELECT SID FROM account WHERE balance > 2000);

Sub Query with ALL/SOME/ANY Q: Find students whose gpa is greater than all/some bus majors’ gpa: –SELECT sid, sname FROM student WHERE gpa > ALL(SELECT gpa FROM student WHERE major=‘bus’); –SELECT sid, sname FROM student WHERE gpa > SOME (SELECT gpa FROM student WHERE major=‘bus’); –SELECT sid, sname FROM student WHERE gpa > ANY (SELECT gpa FROM student WHERE major=‘bus’);

Comparing SQL Statements Compute the number of courses taken by each student: (1) SELECT sid, sname, courses FROM student NATURAL JOIN (SELECT sid, COUNT(cid) AS courses FROM registration GROUP BY sid); (2) SELECT sid, sname, COUNT(cid) AS courses FROM student NATURAL JOIN registration GROUP BY sid, sname;

InLine View When a multiple-column subquery is used in the FROM clause of an outer query, it basically creates a temporary table that can be referenced by other clauses of the outer query. The temporary table is called InLine view.

Select from InLine View SELECT GPAGroup, Count(SID), avg(gpa) FROM (SELECT SID,GPA, CASE WHEN gpa < 2.0 THEN 'Poor' WHEN gpa < 3.0 THEN 'Good' ELSE 'Excellent' END AS GPAGroup, FROM student) GROUPBY GPAGroup; Note: Calculated field cannot be used in the Where or Group By clause. Select eid,ename, salary*.1 As Tax From Employee Where Tax > 1000; ---- This will cause error.

Top (Last) n Analysis Find students with the top 3 GPA. Can we do: –SELECT * FROM student ORDER BY GPA desc WHERE ROWNUM<=3; ? --- No! SELECT * FROM (SELECT * FROM student ORDER BY GPA DESC) WHERE ROWNUM<=3; Note: Use the ROWNUM of the InLineView.

Example: Find Business students who owe university more than $2000 and display their ID, name and balance. Select sid, sname, Balance From (select * from Student where major='bus') natural join (select * from account where balance >2000);

Subquery in the SELECT List SELECT eid,ename,salary,(select AVG(salary) from employee) as AvgSal FROM employee; SELECT eid,ename,salary-(select AVG(salary) from employee) as DeviateFromMean FROM employee;

Multiple Levels Subquery Find students who are taking one-unit courses and display their ID and name. Join: –Select sid, sname, cid from student natural join registration natural join course where units=1; Without Join: –Select sid, sname From Student –Where sid in (select sid from registration where cid in – (select cid from course where units=1));