170 likes | 289 Views
Chapter Eight Data Manipulation Language (DML) Nested Queries Dr. Chitsaz. Objectives Nested queries Conditions on nested queries. Nested Queries: . SELECT …… FROM ….. WHERE operator (SELECT …. FROM …. );. Rules:. Inner query is executed first
E N D
Chapter EightData Manipulation Language (DML)Nested QueriesDr. Chitsaz Objectives Nested queries Conditions on nested queries
Nested Queries: SELECT …… FROM ….. WHERE operator (SELECT …. FROM …. );
Rules: • Inner query is executed first • Enclosed sub-queries in parentheses. • Do not add an ORDER BY to a subquery • Result is used by outer query • Sub-query can be placed in WHERE HAVING FROM
Rules: Operator: • Single row = <> > < >= <= • Multiple rows ANY IN ALL
Nested Queries: • Example: SELECT Name FROM Student WHERE GPA > (SELECT GPA FROM Student WHERE ID=1111);
Practice: List of customer’s name that have balance greater than balance of Mrs. Johnson with id=12345
Using group function in a sub-query: • SELECT Name FROM Faculty WHERE Salary = (SELECT MIN(Salary ) FROM Faculty );
Practice: List the name of sales person who has the highest salary.
Using HAVING with sub-queries: SELECT Name, MIN(salary) FROM Faculty GROUP BY Name HAVING MIN(Salary) > (SELECT MIN(Salary ) FROM Faculty WHERE dept='COSC');
Incorrect Statements: SELECT Name FROM Faculty WHERE Salary = (SELECT MIN(Salary ) FROM Faculty GROUP BY dept);
Incorrect Statements: SELECT Name FROM Student WHERE GPA = (SELECT GPA FROM Student WHERE Name='NNHN');
MULTIPLE ROW SUBQUERY: • Name of students having Grade A SELECT Name FROM Student WHERE ID IN (SELECT ID FROM Student_Course WHERE Grade='A' ); WHERE EXISTS WHERE ID NOT IN …. WHERE NOT EXISTS
MULTIPLE ROW SUBQUERY: SELECT Name FROM Faculty WHERE Salary < (SELECT Salary FROM Faculty WHERE Faculty.ID =1234) AND Dept = (SELECT Dept FROM Faculty WHERE Area='DATABASE');
Multiple Column Subqueries: SELECT col1,col2, col3,… FROM table WHERE (col1,col2, ….) IN (SELECT (col1,col2, ….) FROM table WHERE condition );
(Pair-wise Comparison) Name of students who have the same major and minor as MARY: SELECT name, ID, GPA FROM student WHERE (major, minor) IN (SELECT major, minor FROM student WHERE name='MARY');
Practice: List first name, last name, zip code of customers who have sales rep with minimum salary.
(Non-pair-wise Comparison) SELECT Name, ID, salary FROM Faculty WHERE Salary IN (SELECT Salary FROM Faculty WHERE Dept='COSC') OR Area IN (SELECT Area FROM Faculty WHERE name='MARK');