+ All Categories
Home > Documents > Sub Queries -oracle

Sub Queries -oracle

Date post: 07-Jan-2016
Category:
Upload: sxurdc
View: 14 times
Download: 0 times
Share this document with a friend
Description:
Oracle Sub Queries

of 13

Transcript

Sub Queries

Sub QueriesWhat is a Subquery ?Some times it takes more than one query to achieve a desired result .

Consider the below table . We want to get all the cities whose population is greater than that of HyderabadTable : DEMOGRAPHICSSOLUTIONCITYPOPULATION_20111. The first step is to get the population of Hyderabad.Select population from demographicswhere 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

Mumbai18414288Delhi16314838Kolkata14112536Chennai8696010Bangalore8499399Hyderabad7749334Ahmedabad6240201Pune5049968Surat458536712/19/20131Sub QueriesIn 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')

12/19/20132Types of Sub Queries

You can place a sub query in a From , where and having by clauses.12/19/20133Single Row Sub QueriesMust only return ONE result to the outer query.Operators can be =, >, =, Single-Row Subquery in a WHERE Clause

select city , population_2011 from demographicswhere population_2011 > (select population_2011 from demographics where city='Hyderabad')Single-Row Subquery in a Having By Clause

select state, sum(population_2011) from demographicsgroup by statehaving 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_POPfrom demographics

12/19/20134NULL in Sub QueriesWhat happens when a sub query returns a NULL Value ?

Consider the below query :

select city , population_2011 from demographicswhere 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, therow is not returned because comparison of two null values yields a null; therefore, the WHERE condition is not true.

SO IF A SUB QUERY RETURNS NULL , THE OUTER QUERY RETURS NO ROWS12/19/20135Multiple Row Sub Queries Can Return more than one row of results Require use of IN, ANY, ALL, or EXISTS operatorsOperator MeaningINEqual to any member in the list . Use it when you want to select based on more than one matching value .ANY You have to precede the ANY keyword with > >= , = , , >= , = , , ALL : Less than the Lowest value returned by the Sub query12/19/20136IN Operator Example : Get all the cities in the states Andhra Pradesh and Maharashtra

select State ,city , population_2011 from demographicswhere state in ('Andhra Pradesh' , 'Maharashtra')

The above query can be re written using the ANY operator as follows

select State ,city , population_2011 from demographicswhere state =ANY ('Andhra Pradesh' , 'Maharashtra')12/19/20137ALL and ANY OperatorSELECT employee_id, last_name, job_id, salaryFROM employeesWHERE salary < ANY(SELECT salaryFROM employeesWHERE job_id = 'IT_PROG')AND job_id 'IT_PROG';

SELECT employee_id, last_name, job_id, salaryFROM employeesWHERE salary < ALL(SELECT salaryFROM employeesWHERE job_id = 'IT_PROG')AND job_id 'IT_PROG';12/19/20138Multi Column Sub QueriesReturn more than one column in resultsCan return more than one rowColumn list on the left side of operator must be in parenthesesUse the IN operator for WHERE and HAVING clauses

Example : Get the Latest Payment record for each Loan

select * from loan_paymentswhere (loan_no,pmt_date) in (select loan_no, max(pmt_date) from loan_payments group by loan_no)

12/19/20139Correlated Sub QueriesIf there is any correlation between the main query and sub query then subquery is called as Correlated sub QueryA correlated Sub Query is a sub query that receives some input from the main query and send the result back to main queryUnlike 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 table1WHERE column1 operator(SELECT column1, column2FROM table2WHERE expr1 =.expr2);12/19/201310Correlated Sub QueriesHow to find Loans for which there was more than two payments .

select * from loan lwhere 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 intheir department.

SELECT last_name, salary, department_idFROM employees empWHERE salary


Recommended