DBMS LAB 5
SQL SUB QUERIES
What is a Sub Query?
• A subquery is a SQL query nested inside a larger query.
• A subquery may occur in :
- A SELECT clause
- A FROM clause
- A WHERE clause
• A subquery is also called an inner query or inner select, while
the statement containing a subquery is also called an outer
query or outer select.
• The inner query executes first before its parent query so that the
results of an inner query can be passed to the outer query.
Sub query Syntax
USING SUBQUERIES TO SOLVE A PROBLEM
Using a Subquery to Solve a Problem
• Suppose you want to write a query to find out who earns a salary
greater than Abel’s salary.
• To solve this problem, you need two queries: one to find how much
Abel earns, and a second query to find who earns more than that
amount.
• You can solve this problem by combining the two queries, placing
one query inside the other query.
• The inner query (or subquery) returns a value that is used by the
outer query (or main query). Using a subquery is equivalent to
performing two sequential queries and using the result of the first
query as the search value in the second query.
Subquery Example
Exercise: Find all customers who
have ordered products having
unitprice of 14.
Select customerid from Orders where
OrderID in(select OrderID from
orderdetails where UnitPrice=14 )
Using a Subquery
• A subquery is a SELECT statement that is embedded in a
clause of another SELECT statement. You can build
powerful statements out of simple ones by using
subqueries. They can be very useful when you need to
select rows from a table with a condition that depends on
the data in the table itself.
• The subquery is often referred to as a nested SELECT,
sub-SELECT, or inner SELECT statement. The subquery
generally executes first, and its output is used to complete
the query condition for the main (or outer) query.
Sub query Example
Sub Query Example
Q: Find all employees lastname whose
job level is greater than Brown?
Select lname,job_lvl from employee
where job_lvl> ( select job_lvl from
employee where lname='brown')
Guidelines for using subqueries
• Enclose subqueries in parentheses.
• Place subqueries on the right side of the comparison condition.
• Use single-row operators with single-row subqueries, and use multiple-row
operators with multiple-row subqueries.
Types of Subqueries
Single – Row Subqueries
Single – Row Subqueries
Example:
Q: Display all employees whose job id is the same as of
employee PMA42628M. Use Pubs.
Select fname,job_id from employee where job_id= (select
job_id from employee where emp_id='PMA42628M')
Using Aggregate function in Subquery
Example:
Q: Display all employees who have got min job level.
Use Pubs.
select fname,job_id, job_lvl from employee where
job_lvl= ( select min(job_lvl) from employee)
The HAVING Clause with Subqueries
The HAVING Clause with Subqueries
Example
Q: Display all publishers that have
minimum joblevel greater than that
of publisher 0877. Use pubs.
Select pub_id,min(job_lvl) from
employee group by pub_id having
min(job_lvl)> (select min(job_lvl)
from employee where pub_id=0877)
Multiple Row Subqueries
Example
Q: Display all employees who has
the same job level as the minimum
job level of each publisher. Use
pubs.
Select lname,job_lvl,pub_id from
employee where job_lvl in ( select
min(job_lvl) as Minimumjoblevel
from employee group by pub_id);
Multiple – Row Subqueries
Using the ANY Operator in Multiple
– Row Subqueries
The slide example displays employees who are not IT programmers and whose salary is less than that of any IT
programmer. The maximum salary that a programmer earns is $9,000.
Example
Q: Display all employees whose
job level is less than that of any
of the job id 10 and whose job id
is not equal to 10.
Select
emp_id,lname,job_id,job_lvl from
employee where job_lvl<Any
( select job_lvl from employee
where job_id=10) and
job_id<>10;
Multiple – Row Subqueries
Using the ALL Operator in Multiple
– Row Subqueries
Multiple-Row Subqueries (continued)
The ALL operator compares a value to every value returned by a subquery. The slide example displays
employees whose salary is less than the salary of all employees with a job ID of IT_PROG and whose job is not
IT_PROG.
Example
Q: Display all employees whose
job id is not equal to 10 and whose
job level is less than that of all
employees having job id =10.
Select emp_id,lname,job_id,job_lvl
from employee where job_lvl< All (
select job_lvl from employee
where job_id=10) and job_id<>10;
Example
• To list all Northwind customers who have not placed an order.
• Using Join :
Select o.orderid, c.customerID, c.contactName
from orders o
full outer join Customers c on o.customerID = c.customerid
where o.OrderID is NULL
• Using Subquery:
Select * from Customers
where CustomerID Not in (Select CustomerID from orders)
Example
• We wanted to know the ProductIDs of every item sold on the first
day any product was purchased from the system. If you already
know the first day that an order was placed in the system, then
it’s no problem; the query would look something like this:
SELECT DISTINCT o.OrderDate, od.ProductID
FROM Orders o
JOIN [Order Details] od
ON o.OrderID = od.OrderID
WHERE OrderDate = ‘7/4/1996’ --This is first OrderDate in the system
Result
EXAMPLE
• Using “Sub Query” it will be done as follows
SELECT DISTINCT o.OrderDate, od.ProductID
FROM Orders o
JOIN [Order Details] od
ON o.OrderID = od.OrderID
WHERE o.OrderDate = ( SELECT MIN(OrderDate) FROM
Orders)
TASKS
1. Find the company’s name that placed order 10290. (Tables : Customers & Orders)
2. Find the Companies that placed orders in 1997 (Tables : Customers & Orders)
3. Create a report that shows the product name and supplier id for all products
supplied by Exotic Liquids, Grandma Kelly's Homestead, and Tokyo Traders.
(Tables : Products & Suppliers)
HINT: You will need to escape the apostrophe in "Grandma Kelly's Homestead."
To do so, place another apostrophe in front of it. For example,
SELECT * FROM Suppliers WHERE CompanyName='Grandma Kelly‘’s
Homestead’;
4. Create a report that shows all products by name that are in the Seafood category.
(Tables : Products & Categories)
5. Create a report that shows all companies by name that sell products
in CategoryID 8. (Tables : Supplier & Products)
6. Create a report that shows all 5companies by name that sell products in the
Seafood category.(Tables: Suppliers, Products & Categories)
TASKS
7. Write query using a “sub query” to display which Customers were served by which
Employee use Northwind
8. Write query using a “sub query” to list of all the stores that have discount records
use pubs
9. Write query using a “sub query” to name publishers have got titles in store in
Seattle? Use pubs
10. Write query using a “sub query” to list all the authors available in Barnum’s store
use pubs
11. Write query using a “sub query” to give the customer id and amount spent of the
customer who spent the most using Northwind
12. Write query using a “sub query” to list all Northwind customers who have not
placed an order.