Chap 11
Chap 11
What is a Sub-Query?
A Sub Query is very similar to a regular query except that there are actually 2
queries in one Sub-Query statement. There is an INNER query and an OUTER
query. The INNER query always executes first to completion and is surrounded
by parenthesis, then the OUTER query executes last using the data retrieved by
the INNER Query.
For Example: Let’s say we want the name of the highest paid employee from the
Employees table. With a regular query we can only get the salary from the
Employees table but we cannot get the name of the person paid that salary.
With a Sub-Query you can get the name of the person.
SUB-QUERY Syntax
SELECT columns \
FROM table[s] > outer query
WHERE condition[s] = /
(SELECT function(column), column \
FROM table[s] > inner qry
WHERE condition[s] ) /
EXAMPLE:
Problem: Who makes less than the average salary paid to all
employees.
SELECT firstName, lastName, salary
From Employees
WHERE salary < (SELECT AVG(salary) from Employees)
= or IN
If the INNER query returns only 1 value, then we use an = in the OUTER query in
the WHERE clause. If the INNER query returns more than 1 values, say 2 or 3
values, then we must use an IN in the OUTER query to test all answers returned
from the INNER query.
EXAMPLE:
Summary
Other Resources
Click on the link below to get more help with “SQL SUB-QUERIES”.
https://www.w3resource.com/sql/subqueries/understanding-sql-subqueries.php
http://beginner-sql-tutorial.com/sql-subquery.htm