Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Nested Queries (Sub-Queries)

2 Objectives Learn how to run a query as a nested sub-query Condition on nested query Application of nested query Restriction of nested query Pair wise and not pair wise comparison Nested query at multiple level Use correlated sub-query

3 Definitions Sub-query is a query inside another query Outer query vs. Inner query Inner query executed first Enclose queries are parenthesis Do not add ORDER BY to sub-query (why)? Result of sub-query will be used by outer query

4 Example 1 Employee (Name, SSN, Salary, B_date, Starting_Date, Dept) List Employees name who have salary higher than Mr. Smith: SELECT Name FROM Employee WHERE Salary> (SELECT Salary FROM Employee WHERE Name=‘Smith’);

5 Example 1 List Employees name who have salary higher than Mr. Smith: SELECT A.Name FROM Employee A, Employee B WHERE B.Name=‘Smith’ AND A.salary>B.salary;

6 Example 2 SELECT Name FROM Employee WHERE Salary = (SELECT MAX(Salary) FROM Employee);

7 Use of IN in Sub-Query SELECT Name FROM Employee WHERE Id IN (SELECT Id FROM Employee WHERE Salary BETWEEN 20000 AND 50000);

8 Use of IN in Sub-Query SELECT Name FROM Employee WHERE Id IN (SELECT Id FROM Employee WHERE NOT Salary BETWEEN 20000 AND 50000);

9 Use Sub-Query to join tables Department (Name, Phone, Address, No_Employee) SELECT Name FROM Employee WHERE Dept IN (SELECT Name FROM Department WHERE No_Emplyee>20);

10 Example SELECT Employee.Name FROM Employee, Department WHERE Department.Name= Employee.Dept AND No_Employee>20;

11 Multiple Levels Nested Queries SELECT Name FROM Employee WHERE Salary> (SELECT AVG(Salary) FROM Employee WHERE Dept IN (SELECT Name FROM Department WHERE No_Emplyee>20);

12 Pair Wise Comparison in Sub- Query SELECT Name, Id, GPA FROM Student WHERE (Major, Minor) IN (SELECT (Minor, Major) FROM Student WHERE Name=‘Smith’);


Download ppt "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."

Similar presentations


Ads by Google