Vous êtes sur la page 1sur 13

Sub Queries

What is a Subquery ?
Some times it takes more than one query to
achieve a desired result .
Consider the below table . We want
greater than that of Hyderabad

Table : DEMOGRAPHICS

POPULATION_201
CITY
1

Mumbai
18414288
Delhi
16314838
Kolkata
14112536
Chennai
8696010
Bangalore
8499399
Hyderabad
7749334
Ahmedabad
6240201
Pune
5049968
Surat
4585367

10/6/15

to get all the cities whose population is

SOLUTION
1. The first step is to get the population of
Hyderabad.
Select population from demographics
where city ='Hyderabad';
--7749334
2. The second step is to write a query where
the population is greater than 7749334 (i.e
the result from query 1)
select * from demographics where
population >7749334

Sub Queries
In the previous example we needed two queries to achieve the desire
results .
Oracle lets you combine the two queries into one by using sub queries .

A subquery is a query whose result is used an input to an other


query (called main query or outer query)
Syntax: Main query
Operator (subquery)
The sub query gets executed first and then the main query or
outer query gets executed .
Our previous example can be re written in one query as follows .
select city , population_2011
from demographics
where population_2011 > (select population_2011 from
demographics where city='Hyderabad')
10/6/15

Types of Sub Queries

You can place a sub query in a From ,


where and having by clauses.
10/6/15

Single Row Sub Queries


Must only return ONE result to the outer query.
Operators can be =, >, <, >=, <=, < >
Single-Row Subquery in a
WHERE Clause

Single-Row Subquery in a
Having By Clause

select city , population_2011


from demographics
where population_2011 >
(select population_2011 from
demographics where
city='Hyderabad')

select state,
sum(population_2011) from
demographics
group by state
having sum(population_2011) >
(select avg(population_2011)
from demographics)

Single-Row Sub query in a Select Clause


select city , population_2011 ,
(select avg(population_2011) from demographics) as
AVG_POP
from demographics
10/6/15

NULL in Sub Queries


What happens when a sub query returns a NULL Value ?
Consider the below query :
select city , population_2011 from demographics
where population_2011 >
(select population_2011 from demographics where city='Hydera')
The inner query returns a null value as there no city called Hydera.

The outer query finds no city with a population


greater than null, and so returns no rows. If a city
existed with a value of null, the
row is not returned because comparison of two null
values yields a null; therefore, the WHERE condition
is not true.
10/6/15

Multiple Row Sub Queries


Can Return more than one row of results
Require use of IN, ANY, ALL, or EXISTS operators
Operator
IN
ANY

ALL

10/6/15

Meaning
Equal to any member in the list . Use it when you want to
select based on more than one matching value .
You have to precede the ANY keyword with > >= , = , <>,<=
or <
> ANY : More than the lowest value returned by the Sub
query
= Any : Eual to Any value returned by the sub query(Same as
IN)
You have to precede the ALL keyword with > >= , = , <>,<=
or <
> ALL : More than the highest value returned by the Sub
query
> ALL : Less than the Lowest value returned by the Sub query
6

IN Operator
Example : Get all the cities in the states Andhra Pradesh and
Maharashtra
select State ,city , population_2011 from demographics
where state in ('Andhra Pradesh' , 'Maharashtra')
The above query can be re written using the ANY operator as follows
select State ,city , population_2011 from demographics
where state =ANY ('Andhra Pradesh' , 'Maharashtra')

10/6/15

ALL and ANY Operator


SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary < ANY
(SELECT salary
FROM employees
WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';
SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary < ALL
(SELECT salary
FROM employees
WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';

10/6/15

Multi Column Sub Queries


Return more than one column in results
Can return more than one row
Column list on the left side of operator must
be in parentheses
Use the IN operator for WHERE and HAVING
clauses
Example : Get the Latest Payment record for each Loan
select * from loan_payments
where (loan_no,pmt_date)
in (select loan_no, max(pmt_date) from loan_payments
group by loan_no)
10/6/15

Correlated Sub Queries


If there is any correlation between the main query and sub query
then subquery is called as Correlated sub Query
A correlated Sub Query is a sub query that receives some input from
the main query and send the result back to main query
Unlike a normal sub query a correlated sub query receives value
from main query , it uses the value (generally in the condition) and
sends the results of the query back to main query.
In a correlated sub query the main query gets executed first and for
each row of the main query the sub query is executed once .
SELECT column1, column2, ...
FROM table1
WHERE column1 operator
(SELECT column1, column2
FROM table2
WHERE expr1 =
.expr2);
10/6/15

10

Correlated Sub Queries


How to find Loans for which there was more than two payments .
select * from loan l
where 2 >= (select count(*) from loan_payments lp where
l.loan_no = lp.loan_no)
How to find all employees who earn less than the average salary in
their department.
SELECT last_name, salary, department_id
FROM employees emp
WHERE salary <
(SELECT AVG(salary)
FROM employees
WHERE department_id =
emp.department_id);
10/6/15

11

Exists and Not Exists Operators


EXISTS and NOT EXISTS operators are exclusively
used in correlated sub query.
EXISTS checks whether any row is returned by sub
query and condition will be true if subquery returns
one or more rows. Whereas, NOT EXISTS returns
true if subquery doesnt retrieve any row.
EXISTS is different from other operators like IN,ANY
etc., because it doesnt compare values of columns,
instead, it checks whether any row is retrieved from
subquery or not. If any row is retrieved from
subquery the EXISTS returns true otherwise it
returns
false.
10/6/15
12

Exists and Not Exists


Examples :
Find Employees Who Have at Least One Person Reporting to
Them
SELECT employee_id, last_name, job_id, department_id
FROM employees outer
WHERE EXISTS ( SELECT 'X'
FROM employees
WHERE manager_id =
outer.employee_id);
Find All Departments That Do Not Have Any Employees
SELECT department_id, department_name
FROM departments d
WHERE NOT EXISTS (SELECT 'X'
FROM employees
WHERE department_id = d.department_id);
10/6/15

13

Vous aimerez peut-être aussi