Subqueries in SQL
Subqueries in SQL
Subqueries in SQL
Introduction
• Subqueries provide a powerful means to combine data from two
tables into a single result. You can also call these nested queries. As
the name implies, subqueries contain one or more queries, one inside
the other.
• you can use subqueries in the SELECT, FROM, WHERE, or HAVING
clauses. Depending on how they are used, a subquery may return a
single value or multiple rows.
Example Subqueries
• Subqueries make it possible for you to write queries that are more dynamic and
data driven. For instance using a subquery you can return all products whose
ListPrice is greater than the average ListPrice for all products.
• You can do this by having it first calculate the average price and then use this to
compare against each product’s price.
Subquery Breakdown
• Let’s break down this query so you can see how it works.
• Step 1: First let’s run the subquery:
Compute the remaining average vacation hours for all employees. (subquery)
Group records by JobTitle and computer the average vacation hours.
Only keep groups whose average vacation hours are greater than the overall average.