Sub Queries - Oracle
Sub Queries - Oracle
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
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 .
Single-Row Subquery in a
Having By Clause
select state,
sum(population_2011) from
demographics
group by state
having sum(population_2011) >
(select avg(population_2011)
from demographics)
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
10/6/15
10
11
13